Search code examples
javascriptloopsjavascript-objects

Map not returning object in the correct order?


I have a function that loops through an array and sets key and value pairs to my Map object. I then call another function that multiples the numbers in the object by two. When I return the Map object I noticed that numbers in the object are now in numerical order. According to the API it should preserve the original order of the array, but it's not. What am I doing wrong?

var manArray = [5, 2, 7, 4];
function manipulation(arr) {

  var myMap = new Map();

  for(let i = 0; i < arr.length; i++) {
    var key = arr[i].toString();
    var value = double(arr[i]);

    myMap[key] = value; 
  }
  
  return myMap;
}

function double(num) {
  return num * 2;
}

console.log(manipulation(manArray));


Solution

  • Object key/property order is not guaranteed in JS. Objects are inherently unordered collections or properties (different implementations of JS could have different object property order). If you do want to preserve object order, you might look into a Map, which does guarantee order.