1

I have an array in JavaScript.

var array = [[12,3],[10,2],[8,1],[12,3],[7,1],[6,1],[4,1],[10,2],[12,3]]

I would like to sort this array by the second value in descending order. The expected output is

[[12,3],[12,3],[12,3],[10,2][10,2],[8,1],[7,1],[6,1],[4,1]

I've tried

array.sort(function(array) {
  return array[1] - array[1]
}

Unfortunately, that didn't work.

Sorting single-dimensional arrays is easy but I'm not sure how to do it with multi-dimensional arrays.

Any help will be appreciated.

1 Answer 1

3

Your syntax for the sort function is a bit off. Your function should take two parameters. The following sorts descending by the second position in the inner arrays.

var array = [[12,3],[10,2],[8,1],[12,3],[7,1],[6,1],[4,1],[10,2],[12,3]];
console.log(array.sort(function(a, b) {
  return b[1] - a[1];
}));

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

2 Comments

Nice, you could also do return b[1] - a[1]
@RichardHamilton yes, it's actually better to return a number instead of a boolean in the sort comparison. I updated the answer to reflect that

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.