Skip to content

Instantly share code, notes, and snippets.

@seb-thomas
Created March 7, 2019 12:34
Show Gist options
  • Save seb-thomas/9b6df051f68857ec24a4d9d5e059a329 to your computer and use it in GitHub Desktop.
Save seb-thomas/9b6df051f68857ec24a4d9d5e059a329 to your computer and use it in GitHub Desktop.
Various array methods for unique by object value
const myArray = [{name: "terry", id: 1}, {name: "terry", id: 2}, {name: "john", id: 3}]
// Reduce + Filter
myArray.reduce( ( acc, cur ) => [
...acc.filter( ( obj ) => obj.name !== cur.name ), cur
], [] );
// Acc builds up, but starts off small so more manageable.
// Reduce + Find
myArray.reduce((acc, inc) => {
if(!acc.find( i => i.name === inc.name)) {
acc.push(inc);
}
return acc;
},[]);
// Again, builds up
// Reduce + Find
myArray.reduce((acc, curr) => acc.find(e => e.name === curr.name) ? acc : [...acc, curr], [])
// Same as above but ternary
// Filter + FindIndex
myArray.filter((obj, idx, arr) => {
return arr.findIndex((o) => o.name === obj.name) === idx
})
// Arr is run through every time, and is original size every time
@seb-thomas
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment