Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  78] [ 3]  / answers: 1 / hits: 40045  / 9 Years ago, mon, october 26, 2015, 12:00:00

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!


More From » sorting

 Answers
60

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.


[#64597] Friday, October 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jakobarmandr

Total Points: 363
Total Questions: 103
Total Answers: 87

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;