Created
March 7, 2019 12:34
-
-
Save seb-thomas/9b6df051f68857ec24a4d9d5e059a329 to your computer and use it in GitHub Desktop.
Various array methods for unique by object value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
seb-thomas
commented
Mar 7, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment