How to Store an Array as a Value in a JavaScript Map

To store an array as a value in a Map, create a new Map and then use the set() method to add key-value pairs, where the value is an array.

const mainMap = new Map();

mainMap.set('key1', [1, 2, 3]);
mainMap.set('key2', ['a', 'b', 'c']);



[ 1, 2, 3 ]
[ 'a', 'b', 'c' ]

In this code, we created a new Map called mainMap.

In the next step, we used the set() method to add two key-value pairs to the Map.

The keys are ‘key1’ and ‘key2’, and the values are arrays [1, 2, 3] and [‘a’, ‘b’, ‘c’].

Finally, we used the get() method to retrieve the values associated with the keys ‘key1’ and ‘key2’, which are the arrays [1, 2, 3] and [‘a’, ‘b’, ‘c’].