1
function numObj(s){
  var emptyObj = {};
    s.forEach(function(num) {
      emptyObj[num] = String.fromCharCode(num);
   }); 
  return emptyObj;
}
console.log(numObj([118,117,120]));

I am writing this function to convert the int to its corresponding char in alphabet. However, I am expecting as an output {'118': 'v', '117': 'u', '120': 'x' }, but when I ran the code I get: { '117': 'u', '118': 'v', '120': 'x' } . Does anyone have any explanation why does the function change the order of the input?

Phil Ross
  • 23,417
  • 9
  • 67
  • 75
Max Doung
  • 211
  • 1
  • 10

3 Answers3

1

See Does JavaScript Guarantee Object Property Order? , Nailing object property order

Use Map()

function numObj(s){
  let emptyObj = new Map();
    s.forEach(function(num) {
      emptyObj.set(num, {[num]:String.fromCharCode(num)});
   }); 
  return emptyObj;
}
let obj = numObj([118,117,120]);

for (let [key, value] of obj.entries()) {
  console.log(key, value)
}

or Array() to store objects

function numObj(s){
  let emptyObj = Array.from({length:s.length});
    s.forEach(function(num, i) {
      emptyObj[i] = {[num]:String.fromCharCode(num)};
   }); 
  return emptyObj;
}
let obj = numObj([118,117,120]);

for (let [key, value] of obj.entries()) {
  console.log(key, value)
}
Community
  • 1
  • 1
guest271314
  • 1
  • 10
  • 82
  • 156
0

You are assigning it as property of an object(even dynamic properties). Hence JS is sorting it internally. Instead I would suggest you to use JS array and its push function.

Pratik Gaikwad
  • 1,386
  • 2
  • 18
  • 39
0

You can't guarantee the order of the properties on a JavaScript object. Aside from Map() and using an Array, if you wanted this object to know about the original order of the inputted array of character codes, you could add an order property. By creating a reference of the intended order on the object, you can use it when doing something like printing out the values.

function numObj(s){
  var emptyObj = {};
  emptyObj.order = [];
  s.forEach(function(num) {
    emptyObj[num] = String.fromCharCode(num);
    emptyObj.order.push(num);
  });

  return emptyObj;
}

var obj = numObj([118,117,120]);

obj.order.forEach(function(i){
  console.log(i + " : " + obj[i]);
});
Justin L.
  • 763
  • 11
  • 27