Let’s say we have this array:

const items = ["a", "a", 1, 2, 1, "b"];

So the end result should be:

const uniqueItems = ["a", 1, 2, "b"];

There are multiple solutions for this problem:

1. Using Set

Sets are a new object type with ES6 (ES2015) that allow creating collections of unique values. The values in a set can be either simple primitives like strings or integers as well as more complex object types like object literals or arrays.

const items = ["a", "a", 1, 2, 1, "b"];

const uniqueItems = [...new Set(items)];
// ["a", 1, 2, "b"]

new Set(items) returns an Iterator object so by using [] with the spread operator we ca transform the Iterator into an Array.

However this won’t work in case of an array of objects because every object will have their own references.

For example this will be false:

{ name: "a" } === { name: "a" } // false


A workaround for this would be to stringify the objects:

const items = [{ name: "a" }, { name: "a" }, { name: "b" }];

const uniqueItems = [
  ...new Set(items.map(item => JSON.stringify(item))),
].map(item => JSON.parse(item));
// [{ name: "a" }, { name: "b" }]

2. Using filter

Another option would be to use filter

const items = ["a", "a", 1, 2, 1];

const uniqueItems = items.filter(
  (item, index, arr) => arr.indexOf(item) === index,
);

Here we check if the first occurrence of a certain items it’s equal with the index of the item, if that’s false that means that the item already appeared in the array before, so it’s a duplicate.

Conclusion

I hope you enjoyed this tutorial. If you need help with something don’t hesitate to contact me.