Skip to content

Instantly share code, notes, and snippets.

@crates
Last active August 2, 2022 13:52
Show Gist options
  • Save crates/dec423cdb859fbfcdc892a8ec38f5777 to your computer and use it in GitHub Desktop.
Save crates/dec423cdb859fbfcdc892a8ec38f5777 to your computer and use it in GitHub Desktop.
Make Array of Objects Unique (filter by property name)
// 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