Splitting arrays by a condition

We can split arrays in two based on a condition. Everything that matches the condition goes into the first result, everything that doesn’t goes into the second result.

// an array we want to split into two arrays based on a condition
const names = ['Michael', 'Jim', 'Dwight', 'Pam', 'Ryan']

// accepts array and function returning `true` or `false` for each element
const partition = (array, callback) => {
  const matches = []
  const nonMatches = []

  // push each element into array depending on return value of `callback`
  array.forEach(element => (callback(element) ? matches : nonMatches).push(element))

  return [matches, nonMatches]

// destructure matches as `shortNames` and non-matches as `longNames`
const [shortNames, longNames] = partition(names, name => name.length <= 3)
// ⇒ shortNames: ['Jim', 'Pam']
// ⇒ longNames:  ['Michael', 'Dwight', 'Ryan']

const [evenLength, oddLength] = partition(names, n => n.length % 2 === 0)
// ⇒ evenLength: ['Dwight', 'Ryan']
// ⇒ oddLength:  ['Michael', 'Jim', 'Pam']

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.