Last active
August 2, 2022 13:52
-
-
Save crates/dec423cdb859fbfcdc892a8ec38f5777 to your computer and use it in GitHub Desktop.
Make Array of Objects Unique (filter by property name)
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
// Learn more about Set on MDN: | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set | |
// Here are some other ways to filter and manipulate object contents: | |
// https://masteringjs.io/tutorials/fundamentals/filter-object | |
const data = [ | |
{ | |
name: "car1", | |
id: 1, | |
}, | |
{ | |
name: "car1", | |
id: 2, | |
}, | |
{ | |
name: "car2", | |
id: 3, | |
} | |
]; | |
const makeObjectArrayPropertiesUnique = (arr, prop) => { | |
const s = new Set(); | |
return arr?.filter(d => { | |
if (!s.has(d[prop])) { | |
s.add(d[prop]); | |
return d; | |
} | |
}); | |
}; | |
console.log(makeObjectArrayPropertiesUnique(data, 'name')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment