Skip to content

JavaScript set map | Code

  • by

You can use the Spread-Operator to run the map on a JavaScript Set. the spread syntax allows an expression to be expanded in places where multiple arguments or multiple elements or multiple variables are expected.

JavaScript set map

Simple example code Set to map over the Set.

<!DOCTYPE html>
<html>
<body>
  <script>
    const s = new Set([1,2,3,4]);

    const m = [...s].map( n => n * 2 )

    console.log(m)
    console.log(typeof(m))

  </script>
</body>
</html>

Output:

JavaScript set map

How to map/reduce/filter a Set in JavaScript?

Answer: A short-hand way to do it is to convert it to an array via the ES6 spread operator.

Then all the array functions are available to you.

const mySet = new Set([1,2,3,4]);
[...mySet].reduce(...);
const set = new Set([1,2,3,4,5]);

function filterSet(index) {
    set.delete([...set][index]);
}

filterSet(3); // Set { 1, 2, 3, 5, [size]: 4 }

How can I convert Map to Set and vice versa?

Answer: You can easily replace a set with a map. let’s handle both at once.

function print(collection) {
    collection.forEach((value, key) => {
        console.log(key, value);
    });
}

const set = new Set(["orange", "apple", "banana"]);
const map = new Map([[1, "peach"], [2, "pear"]]);

print(set); // works
print(map); // works the same

Do comment if you have any doubts or suggestions on this Js set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading