I have a function that creates a Map object from two arrays and then attempts to sort the map by key. Despite following the sort method as outlined in Mozilla Docs, the sorting is not working as expected; it places the first key at the last index when using the mapSort object.
const sortMapByKey = () => {
const keyArray = [4, 6, 16, 18, 2]
const valueArray = [103, 123, 4444, 99, 2000]
const buildMap = (keys, values) => {
const map = new Map();
for(let i = 0; i < keys.length; i++){
map.set(keys[i], values[i]);
};
const mapSort = new Map([...map.entries()].sort(function(a, b) {
return a - b;
}));
return mapSort
};
return buildMap(keyArray, valueArray)
}
The current output:
Map { 4 => '103', 6 => '123', 16 => '4444', 18 => '99', 2 => '2000' }
The desired output:
Map { 2 => '2000', 4 => '103', 6 => '123', 16 => '4444', 18 => '99' }
I'm puzzled about what might be going wrong with my sort implementation. Any insights?