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]];
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.
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.
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.
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.
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:
0
if you want a
to appear before b
0
if you want b
to appear before a
0
if a
and b
are the sameSo, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With