0

I'm having a hard time figuring out this.

So, I am making a site where I need to store the horizontal position of elements in a object with the ID as value. Then I need to sort the object by the key. Later I have to loop though the object and find the closest elements (both before and after).

I am struggling with storing the information. I have it like a variabel.

Is it correct to store it like this:

myObj.x = tempId;

Next, how do I sort the keys? It should sort as a number, not text because I had problem with the sort doing 14, 1500, 800.

And last, how can I loop the object and maintain access to both key and value? If I do for (var i in obj) I loose the key-value.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
  • 1
    You can't sort Object keys, they are not arrays and order is not gauranteed. – JaredMcAteer May 24 '12 at 14:26
  • How should I pull this off then? I have no clue how to do this the simplest way. It does not sound very difficult but it's giving me a lot of headache. – OptimusCrime May 24 '12 at 14:27
  • 1
    Store the key/values in a multidimensional array and sort by the value. http://stackoverflow.com/questions/2793847/sort-outer-array-based-on-values-in-inner-array-javascript – JaredMcAteer May 24 '12 at 14:29
  • 1
    Regarding `for (var i in obj)`: `i` is the key and `obj[i]` will be the value... – Felix Kling May 24 '12 at 14:36

0 Answers0