Search code examples
javascriptsortingobjectproperties

How to prevent automatic sort of Object numeric property?


Why I met this problem: I tried to solve an algorithm problem and I need to return the number which appeared most of the times in an array. Like [5,4,3,2,1,1] should return 1. And also when two number appear same time as the maximum appearance return the one came first. Like [5,5,2,2,1] return 5 because 5 appear first. I use an object to store the appearance of each number. The key is the number itself.

So When the input is [5,5,2,2,1] my object should be Object {5: 2, 2: 2, 1: 1} but actually I got Object {1: 1, 2: 2, 5: 2} So When I use for..in to iterate the object I got 2 returned instead of 5 . So that's why I asked this question.

This problem occurs in Chrome console and I'm not sure if this is a common issue: When I run the following code

var a = {};
a[0]=1;
a[1]=2;
a[2]=3;

a is: Object {0: 1, 1: 2, 2: 3}

But when I reverse the order of assignment like:

 var a = {};
 a[2]=3;
 a[1]=2;
 a[0]=1;

a is also:Object {0: 1, 1: 2, 2: 3} The numeric property automatic sorted in ascending order. I tried prefix or postfix the numeric property like

var a = {};
a['p'+0]=1;
a['p'+1]=2;
a['p'+2]=3;
console.log(a);//Object {p0: 1, p1: 2, p2: 3}

And this keep the property order. Is this the best way to solve the problem? And is there anyway to prevent this auto sort behavior? Is this only happen in Chrome V8 JavaScript engine? Thank you in advance!


Solution

  • You are using a JS object, that by definition does not keep order. Think of it as a key => value map.

    You should be using an array, that will keep whatever you insert on the index you inserted it into. Think of it as a list.

    Also notice that you did not in fact "reverse the order of the assignment", because you inserted elements on the same index every time.