How to Avoid Array Duplicates in Javascript

| Comments

JavaScript arrays is of great help(as they are in any language), but if you want to avoid duplicates in arrays then you need to multiple steps. That’s why ES6 introduced sets, a new type of collection that cannot contain duplicates.

You can create a set in ES6 by passing an array into the constructor:

1
2
3
let set = new Set([1, 2, 3, 3, 4, 5, 5, 5, 6]);

console.log(set.size); // 6

Notice the array I passed in contains duplicates. But the set essentially strips them out and I’m left with a collection of 6 unique items (instead of the original 9 with duplicates), which is much more useful in certain situations.

You don’t have to pass in an array to create a set, but that’s one way to do it. You also have access to the add() method, so you can do this:  

1
2
3
4
5
6
let set = new Set();

set.add(1);
set.add('two');

console.log(set.size); // 2

Finally, there’s the has() method, which is probably what you’ll use the most. This method allows you to check if an item exists. And because sets can’t contain duplicates, it’s a simple check, then you can move on to other things without any complexities:

1
2
3
console.log(set.has(1)); // true
console.log(set.has('two')); // true
console.log(set.has(3)); // false

The feature has strong browser support, so goahead and use this in your project.

Credits: MDN, WebWeekly Newsletter

Comments