Categories
JavaScript Answers

How to create array of unique objects by property with JavaScript?

Spread the love

To create array of unique objects by property with JavaScript, we use the array filter method.

For instance, we write

const getUniqueBy = (arr, prop) => {
  const set = new Set();
  return arr.filter((o) => !set.has(o[prop]) && set.add(o[prop]));
};

to define the getUniqueBy function.

In it, we create a set with the Set constructor.

And then we return the array returned by filter that adds the o[prop] to the set if it doesn’t exist and if the property value doesn’t exist.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.