I have an array with keys like this:
0kefsdfsdf
1101fsdf
55fdsfds
Now I want to sort that array so that the keys start with the smallest number. Afterwards the keys should look like that:
0kefsdfsdf
55fdsf
1101fsdfds
I tried this code, but its not sorting the keys:
myArray.sort(function(a, b) {
return a < b;
});
How can I sort the array according to the keys so that when I iterate the array afterwards, it starts with the key with the lowest number?
1 Answer 1
You can use
var sorted = myArray.sort(function(a,b){ return parseInt(a,10)-parseInt(b,10) });
This relies on the curious behavior of parseInt which isn't worried when asked to parse "55fdsfds" :
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
.sortcallbacks MUST return: a negative number if a is to be considered less than b, a positive number if a is to be considered greater than b, and zero if they are to be considered equal. You are returning a boolean, which is cast to either 0 or 1 - notably, 1 is returned when a < b, which is the opposite of what you want.{a:1,b:2}- here, a and b are keys. In an array, you have values.