25

I'm trying to sort an array of arrays with integers inside, for example:

var array = [[123, 3], [745, 4], [643, 5], [643, 2]];

How can I sort it in order to return something like the following?

array = [[745, 4], [643, 2], [643, 5], [123, 3]];
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Inês
  • 363
  • 1
  • 4
  • 7
  • 2
    Are you sorting by the first element in each array, or the largest element in each array? – mhodges May 18 '18 at 15:59
  • 1
    Also, what have you tried so far? – mhodges May 18 '18 at 16:00
  • 2
    Possible duplicate of [Sort an array with arrays in it by string](https://stackoverflow.com/questions/5435228/sort-an-array-with-arrays-in-it-by-string) – Frank Visaggio May 18 '18 at 16:01
  • @mhodges sorting by the first element in each array – Inês May 18 '18 at 16:02
  • Note that this is essentially the same as [Sorting objects by property values](/q/2466356/4642212). If you’re looking for sorting an array _based on another array_ (e.g. `const order = [ "red", "green", "blue" ];` defines the order and you want to sort `[ "blue", "green", "red" ]` according to `order`), then see [Sort array based on another array](/q/13304543/4642212). – Sebastian Simon Mar 15 '22 at 12:28

3 Answers3

49

You can pass a custom comparison function to Array.prototype.sort(), like so:

var sortedArray = array.sort(function(a, b) { return a - b; });

This would sort an array of integers in ascending order. The comparison function should return:

  • an integer that is less than 0 if you want a to appear before b
  • an integer that is greater than 0 if you want b to appear before a
  • 0 if a and b are the same

So, for this example you would want something like:

var sortedArray = array.sort(function(a, b) {
  return b[0] - a[0];
});

If you wanted to sort on both elements of each sub-array (ie. sort by the first element descending, then if they are the same then sort by the second element descending), you could do this:

var sortedArray = array.sort(function(a, b) {
  if (a[0] == b[0]) {
    return a[1] - b[1];
  }
  return b[0] - a[0];
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info.

Let Me Tink About It
  • 13,762
  • 16
  • 86
  • 184
Gordon Larrigan
  • 514
  • 1
  • 6
  • 3
11

You can use sort method and first sort by first elements and then by second.

var array = [[123, 3], [745, 4], [643, 5], [643, 2]];
array.sort(([a, b], [c, d]) => c - a || b - d);
console.log(array)
Nenad Vracar
  • 111,264
  • 15
  • 131
  • 153
6

Assuming you want to sort by the first index in your example, the sort function exists to solve your problem.

let ans = [[123, 3], [745, 4], [643, 5], [643, 2]].sort( (a, b) => {
  return b[0] - a[0]
})

console.log(ans)