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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87

1 Answers1

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];
}));
Dave
  • 10,748
  • 3
  • 43
  • 54
  • Nice, you could also do `return b[1] - a[1]` – Richard Hamilton Jun 08 '15 at 15:26
  • @RichardHamilton yes, [it's actually better](http://stackoverflow.com/questions/24080785/sorting-in-javascript-shouldnt-returning-a-boolean-be-enough-for-a-comparison) to return a number instead of a boolean in the sort comparison. I updated the answer to reflect that – Dave Aug 04 '16 at 16:44