How does [...new set(array)] works in javascript?

Hassan Al Najjar
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 operator, and I search about set and I didn't find explain about how does it work.

How the set Comparison of items and find similar items? If set use a loop in Comparison

Any help is greatly appreciated

Amadan

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, for Sets, +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 and 0" in the browser compatibility table for details.

NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== 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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related