Consider:
const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const uniqueAges = [...new Set(ages)] console.log(uniqueAges) // [26,27,28,29,30]
I know the spread syntax. I searched about set, and I didn’t find an explanation about how it works.
How can I set comparison of items and find similar items?
If set, use a loop in the comparison.
Advertisement
Answer
Set can only contain unique values; here is what constitutes an equal value according to MDN:
Because each value in the
Set
has to be unique, the value equality will be checked. In an earlier version of ECMAScript specification, this was not based on the same algorithm as the one used in the===
operator. Specifically, forSet
s,+0
(which is strictly equal to-0
) and-0
were different values. However, this was changed in the ECMAScript 2015 specification. See “Key equality for-0
and0
” in the browser compatibility table for details.
NaN
andundefined
can also be stored in aSet
. AllNaN
values are equated (i.e.NaN
is considered the same asNaN
, even thoughNaN !== NaN
).
There is an implicit loop in creation of the Set
, using the iterable interface of the passed array. There is also a loop in ...
, which unpacks an iterable.
However, checking whether an element is already in Set
is not done using a loop – for all intents and purposes you can think of a Set
as a dictionary with only keys, and no values. The code is almost the same as:
const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30] const temp = {}; for (const age of ages) { temp[age] = true; } const uniqueAges = []; for (const age in temp) { uniqueAges.push(age); } console.log(uniqueAges);
I am intentionally writing this “low tech” way to illustrate what is going on; notice that object keys are always strings so the result will be stringified. Using a Map
or also storing ages as values would make it much more similar in effect to OP’s code, but I wanted to keep it simple for the sake of illustration.