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?
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]
]);
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; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With