Filtering arrays to unique values
JavaScript
Read fire tipWe 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']