1

Possible Duplicate:
Sorting a JavaScript object
Sort JavaScript object by key

I have array:

var arr = {}
arr[2323] = 1
arr[123] = 1
...
arr[n+232323] = 1

How to get all element of aobject sorted by key ( number order ? )

for ( key in arr ) {
     alert(typeof(key))
}

return string type.

Community
  • 1
  • 1
Bdfy
  • 18,923
  • 51
  • 118
  • 176
  • 2
    you mean object because there is nothing called associative array in javascript – bugwheels94 Aug 03 '12 at 14:19
  • I am a bit bothered by the fact that people are answering saying you cannot sort these, clearly if all the keys are numeric they can be sorted. Maybe he desires to iterate through the keys (in numeric order) so he can load them into a new object where the keys aren't quite as far apart. – VoronoiPotato Aug 03 '12 at 14:42
  • Objects cannot be directly sorted, however "am not i am"'s answer will provide an ordered list of `keynames` within the object, so they can be called in secession. – Austin Aug 03 '12 at 14:44

4 Answers4

1

This is not an assosiative array, this is an object. There are no associative arrays in javascript.

Additionally, objects are not ordered. The order of keys in an object is meaningless.

Austin
  • 5,936
  • 2
  • 20
  • 24
1

Assuming there's some reason you don't use an Array in the first place, you can get an Array of the enumerable object properties, and sort that Array...

var sorted = Object.keys(my_obj)
                   .sort(function(a,b) {
                            return a - b;
                         });

This assumes the keys are numeric.

Then you can iterate the Array, and use each key to get the value from my_obj...

sorted.forEach(function(key) {
                   console.log(my_obj[key]);
               });
  • `keys` are by definition `strings` in this language. So you either should `parseInt` or use `+keyname` or call `.localeCompare` on the `a` or `b` string. – jAndy Aug 03 '12 at 14:24
  • 1
    @jAndy: "numeric" is different than "number". You can have *numeric strings*. I'm just saying that my sorting is assuming that a numeric sort is desired. –  Aug 03 '12 at 14:24
  • Note that this will return an ordered array listing the keynames of the object that you want to access. – Austin Aug 03 '12 at 14:26
  • 1
    of course you can, but it's bad karma I think. You shouldn't leave it up the black magic to convert stuff correctly. – jAndy Aug 03 '12 at 14:26
  • @jAndy: I don't understand what you mean. Are you talking about the implicit *toNumber* conversion of the subtraction operator? –  Aug 03 '12 at 14:27
  • @amnotiam: yes. as I mentioned, `keys` are always strings. So you're just hoping there the string contains a cast'able value. I'd rather do it with `return a.localeCompare(b);` – jAndy Aug 03 '12 at 14:28
  • @jAndy: But my answer states that assumption. We really have no idea what manner of sort is desired. I just gave one example. The point is that you can obtain a sortable Array of enumerable properties. –  Aug 03 '12 at 14:29
  • @amnotiam: true, but with `String.prototype.localeCompare` you're on the safe side, since those values will always be inherited from `String` :) – jAndy Aug 03 '12 at 14:30
  • @jAndy: Alright, I see what you mean. It's a little beyond what I was trying to communicate, but I get your point. –  Aug 03 '12 at 14:31
  • @Austin: Why would you only return `1`, `0`, or `-1`? –  Aug 03 '12 at 14:32
  • 2
    @amnotiam: yea I totally agree with `Object.keys` and `.sort()`, I'd do the same. Just that `(hopefully castable) - (hopefully castable)` annoyed me a little, because the simple solution for the problem :p – jAndy Aug 03 '12 at 14:33
1

Short answer: You can't.

Long answer: Associative Arrays in JavaScript are really JavaScript objects. When you add a new element, you're really adding a new member to the object. While most browsers will enumerate those members in the order they were added, the standard states that the order is undefined. You can't sort something that is undefined.

Justin Niessner
  • 229,755
  • 35
  • 391
  • 521
1

JavaScript objects (maps/dictionaries/associative arrays) have no order, you can't sort them. You will need to convert it to an array first. As you only need the keys of your object in your loop, the Object.keys() function (potentionally needs a shim for older browsers) is destined for the task:

var obj = {...};
var keys = Object.keys(obj).sort(function(a,b){return a-b;}); // numerically sorted
for (var i=0; i<keys.length; i++) {
    alert(keys[i]);
    // access the values by obj[keys[i]]
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164