Exploring Sets now and could not get a new Set from an array of x arrays in it. I what to use Array.map method inside new Set().
Here is what I’m trying to do, and it seems logical, but in the end having values only from the 1st array:
JavaScript
x
2
1
new Set(array.map(x => x.value));
2
Will be awesome to understand what I am doing wrong and how it should look like
Update: To be more clear in my need:
JavaScript
1
3
1
const array = [[1,1,3,4], [2,2,3,4], [1,1,3,5]];
2
new Set(array.map(x => x));
3
My goal to have [1,2,3,4,5]
but getting [1,3,4]
Solution:
JavaScript
1
2
1
new Set(array.map(x => x.value).flat())
2
Advertisement
Answer
You need only the array, not spreaded parameters:
JavaScript
1
2
1
new Set(array.map(x => x.value));
2
From Set
:
Syntax
JavaScript131new Set()
2new Set(iterable)
3
With a nested array, you need a flat it first:
JavaScript
1
7
1
const
2
array = [[1, 1, 3, 4], [2, 2, 3, 4], [1, 1, 3, 5]],
3
unique = new Set(array.flat()),
4
result = [unique].sort((a, b) => a - b);
5
6
console.log(unique); // still a set
7
console.log(result); // array, sorted