Suppose we have two arrays −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"];
We are required to write a JavaScript function that takes in the keys and the values array and maps the values to the corresponding keys.
Therefore, the output should look like −
const map = { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' };
Therefore, let’s write the code for this function −
Example
The code for this will be −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"]; const buildMap = (keys, values) => { const map = new Map(); for(let i = 0; i < keys.length; i++){ map.set(keys[i], values[i]); }; return map; }; console.log(buildMap(keys, values));
Output
The output in the console will be −
Map(5) { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' }