0

Both attempts fail to sort the inner arrays:

a=[['c'],['b']]
a.sort(function(a,b){a[0]<b[0]}) // returns c,b
console.log(JSON.stringify(a))
a.sort(function(a,b){a[0]>b[0]}) // returns c,b
console.log(JSON.stringify(a))

What am I doing wrong? Thank you!

http://jsfiddle.net/0w7t3ov2/

4
  • 1
    The comparison function is supposed to return a number, not true or false. Commented Dec 27, 2014 at 1:21
  • Using a[0]<b[0]?1:-1 did not work either: jsfiddle.net/0w7t3ov2/1 Commented Dec 27, 2014 at 1:25
  • 1
    You don't have return in any of your functions. Commented Dec 27, 2014 at 1:25
  • jsfiddle.net/barmar/0w7t3ov2/2 Commented Dec 27, 2014 at 1:26

1 Answer 1

2

The function you pass to .sort() needs to return an integer, not a boolean. The integer should be less than zero if the first argument should come before the second in the sort order; greater than zero if it should come after; and zero if they're equal.

So, in your case:

a.sort(function(a, b) {
  return a[0] < b[0] ? -1 :
         a[0] > b[0] ? 1 :
         0;
});
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.