Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of arrays in JavaScript

Tags:

javascript

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]];
like image 913
Inês Avatar asked May 18 '18 15:05

Inês


People also ask

Can you sort an array of arrays in JavaScript?

To sort the array of arrays, you need to specify based on which element you want to sort them. Here we compare the arrays by their second elements. Then the sort() function loops through the array of arrays and sorts it based on the magnitude of the second elements.

How do I sort multiple arrays?

The arrays are treated as columns of a table to be sorted by rows. The first array is the main one to sort by; all the items in the other arrays are reordered based on the sorted order of the first array. If items in the first array compare as equal, the sort order is determined by the second array, and so on.

How do you sort an array in JavaScript?

Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Can we sort array of objects in JavaScript?

We can sort the array of objects using the sort() method in javascript and then provide a comparison function that will ultimately determine the order of the objects.


1 Answers

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.

like image 103
Gordon Larrigan Avatar answered Oct 07 '22 19:10

Gordon Larrigan