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

3.3k Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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