Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set all of the entries of a map to a value

Tags:

javascript

I have an array that I want to use as the keys to my map and set each value to true. Is there a way to do this besides using a forEach loop on my array to set each entry? This is how I am doing it now:

const list = [0, 1, 2, 3];
const myMap = new Map();
list.forEach(element => myMap.set(element, true));

Is there a better way?

like image 296
Kevin Maitski Avatar asked Aug 21 '18 19:08

Kevin Maitski


3 Answers

A more concise, functional, way, would be to pass a map of the list as an argument to the Map:

const list = [0, 1, 2, 3];
const myMap = new Map(list.map(key => [key, true]));

This works because new Map takes an iterable of key/value pairs. Arrays are valid iterables.

The list.map makes the code evaluate similarly to

new Map([
  [0, true],
  [1, true],
  [2, true],
  [3, true]
]);
like image 177
towc Avatar answered Oct 28 '22 06:10

towc


You could take an array for the Map constructor.

const list = [0, 1, 2, 3];
const myMap = new Map(list.map(k => [k, true]));

console.log([...myMap]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 39
Nina Scholz Avatar answered Oct 28 '22 06:10

Nina Scholz


If you choose to use a solution with Map then mind potential browser compatibility issues (like old IE). See more details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

like image 25
Trve Avatar answered Oct 28 '22 08:10

Trve