Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get new Set from array of arrays by using Array.map function?

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:

new Set(...array.map(x => x.value));

Will be awesome to understand what I am doing wrong and how it should look like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Update:
To be more clear in my need:

const array = [[1,1,3,4], [2,2,3,4], [1,1,3,5]];
new Set(...array.map(x => x));

My goal to have [1,2,3,4,5] but getting [1,3,4]

Solution:

 new Set(array.map(x => x.value).flat())

>Solution :

You need only the array, not spreaded parameters:

new Set(array.map(x => x.value));

From Set:

Syntax

new Set()
new Set(iterable)

With a nested array, you need a flat it first:

const
    array = [[1, 1, 3, 4], [2, 2, 3, 4], [1, 1, 3, 5]],
    unique = new Set(array.flat()),
    result = [...unique].sort((a, b) => a - b);

console.log(...unique); // still a set
console.log(...result); // array, sorted
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading