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.
4 Answers 4
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.
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 definitionstrings
in this language. So you either shouldparseInt
or use+keyname
or call.localeCompare
on thea
orb
string.jAndy– jAndy2012年08月03日 14:24:18 +00:00Commented Aug 3, 2012 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.user1106925– user11069252012年08月03日 14:24:56 +00:00Commented Aug 3, 2012 at 14:24
-
Note that this will return an ordered array listing the keynames of the object that you want to access.Austin– Austin2012年08月03日 14:26:02 +00:00Commented Aug 3, 2012 at 14:26
-
1of course you can, but it's bad karma I think. You shouldn't leave it up the black magic to convert stuff correctly.jAndy– jAndy2012年08月03日 14:26:09 +00:00Commented Aug 3, 2012 at 14:26
-
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 :pjAndy– jAndy2012年08月03日 14:33:16 +00:00Commented Aug 3, 2012 at 14:33
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.
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]]
}
keynames
within the object, so they can be called in secession.