Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
How can I convert Map to Set and vice versa?

forEach() method uses value variable twice. It's written that this is done in order to ensure the compatibility of Map and Set.

Source

That’s for compatibility with Map where the callback passed forEach has three arguments. Looks a bit strange, for sure. But may help to replace Map with Set in certain cases with ease, and vice versa.

let set = new Set(["orange", "apple", "banana"]);

set.forEach((value, valueAgain, set) => {
  console.log(valueAgain); //"orange", "apple", "banana"
});

So, my question is how Set can convert into Set and vice versa? As I understand, there is no special method for this case.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It does not say anything about conversion. It says that you can use the same function callback for the Map and the Set.

const set = new Set(["oranges", "apples", "bananas"]);
const map = new Map([
  ['cucumber', 500],
  ['tomatoes', 350],
  ['onion',    50]
]);
const print = (value, key) => console.log(value, key);
set.forEach(print)
// oranges oranges
// apples apples
// bananas bananas
map.forEach(print)
// 500 cucumber
// 350 tomatoes
// 50 onion
about 4 years ago · Juan Pablo Isaza Report

0

The point is not that you can easily replace a set with a map in your code. If you do that, you touch the code anyway, and would have no trouble also rewriting the iteration.

The real benefit is that it allows writing code that can handle both at once. In your example:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!