Categories
JavaScript Answers

How to create a unique array of objects with JavaScript?

Spread the love

To create a unique array of objects 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. Required fields are marked *