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']
More fire tips
Getting the last element from an array
Read fire tipMapping array values with constructors
Syntactic sugar on the Array prototype’s map function and type constructors being functions allow us to quickly map values from one type to another.
Read fire tip