Make arrays unique again!

Bastiaan Dressen
19-01-2017

There is a really easy way to make arrays containing duplicated items unique, although it does require ES6+.
Are you ready for it? Brace yourselves…, here we go!

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

console.log(b); // [1, 2, 3, 4, 5, 6]

How much fun was that? So that was the how, now let’s get into the why of it.

The Set object (according to MDN) lets you store unique values of any type, whether primitive values or object references.

Hold on, primitive values as well as object references? Don’t just take MDN’s word for it, let’s test it.

let c = {key1: 'WTF', key2: 'Good Lord'};
let d = {key1: 'sounds too good to be true', key2: 'but very, very nice!'};
let e= [...new Set([c, d, c, d, c, d])];

console.log(e); // [{key1: 'WTF', key2: 'Good Lord'}, {key1: 'sounds too good to be true', key2: 'but very, very nice!'}]

Ok, one more test for good measure:

let f = [...new Set([null, null, undefined, undefined, true, false, false, 'yes', 'yes', 'no', 'no', true])];

console.log(f); // [null, undefined, true, false, 'yes', 'no']

WTF, Good Lord, sounds too good to be true, but very, very nice!

 

LEAVE A REPLY

you might also like