Richard Hamilton Richard Hamilton - 2 months ago 5x
Javascript Question

How to sort a multi-dimensional array by the second array in descending order?

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


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.


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];