Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda