Oddly enough, figuring out how to de-duplicate an array in JavaScript eluded me for a long time. The introduction of the Set built-in object make de-duplication of array elements easy. For example
console.log(Array.from(new Set(["a", "b", "c"].concat(["a"]))));
Output:
[ 'a', 'b', 'c' ]
This works for a simple array. You may want to find unique values of an attribute in an array of objects. This can be done in multiple ways. This is a good opportunity to practice using reduce
for something other can summing a list of numbers.
const uniq = [
{ a: "one", b: "one" },
{ a: "two", b: "one" },
{ a: "three", b: "one" },
].reduce((objs, obj) => {
if (!objs.includes(obj.b)) {
objs.push(obj.b);
}
return objs;
}, []);
console.log(uniq);
Output:
[ 'one' ]
let uniq2 = [];
[
{ a: "one", b: "one" },
{ a: "two", b: "one" },
{ a: "three", b: "one" },
].map((obj) => {
if (!uniq2.includes(obj.b)) {
uniq2.push(obj.b);
}
});
console.log(uniq2);
Output:
[ 'one' ]
We can also use forEach
:
let uniq3 = [];
[
{ a: "one", b: "one" },
{ a: "two", b: "one" },
{ a: "three", b: "one" },
].forEach((obj) => {
if (!uniq3.includes(obj.b)) {
uniq3.push(obj.b);
}
});
console.log(uniq3);
Output:
[ 'one' ]