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.