0

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?

5
  • .sort callbacks 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. Commented Nov 22, 2013 at 11:21
  • Also, when people talk about "keys", they usually refer to objects, such as this: {a:1,b:2} - here, a and b are keys. In an array, you have values. Commented Nov 22, 2013 at 11:22
  • sitepoint.com/sophisticated-sorting-in-javascript Commented Nov 22, 2013 at 11:24
  • Does every value begin with a number? Commented Nov 22, 2013 at 11:26
  • You want sort the keys or the values ? Commented Nov 22, 2013 at 12:31

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.