34

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]];
4
  • 2
    Are you sorting by the first element in each array, or the largest element in each array? Commented May 18, 2018 at 15:59
  • 2
    Possible duplicate of Sort an array with arrays in it by string Commented May 18, 2018 at 16:01
  • @mhodges sorting by the first element in each array Commented May 18, 2018 at 16:02
  • Note that this is essentially the same as Sorting objects by property values. 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. Commented Mar 15, 2022 at 12:28

6 Answers 6

60

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I noticed that comparison operators can be applied to arrays and it works, however it's not documented anywhere, e.g. [2, 2] > [1, 3] is true and [1, 0] > [0, 1] is true... etc.
+1 to @CMCDragonkai's comment. Using the > and < operators you can explicitly return 1, -1, or 0 from the compare function.
Please don't use the < operator - it isn't correct in all situations. The arrays are implicitly stringified via .join(',') before comparing (see stackoverflow.com/questions/8328908/…). This means that [11, 2] < [2, 3] == true which is not what you want.
Be careful: Array.prototype.sort() sorts the array in-place. The assignment to sortedArray is a bit misleading. To return a new array you should use toSorted() instead. Docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
12

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)

Comments

9

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)

Comments

4

A solution for the arrays with generic lengths (not limited to 2 or equal) can be as below:

var array = [[123, 3], [745, 4], [643, 5], [643, 2]];
array.sort((a,b)=>
    {
        for(let i=0;i<a.length && i<b.length;i++){
            if(a[i]!==b[i]){
                return a[i]-b[i];
            }

        }
        return a.length-b.length;
    }
)
console.log(array)

1 Comment

excellent answer, it is mising the closing ) however, very useful... kudos
1

If you want to sort sub array in ascending order as per first element, we can do :

arrayToSort.sort((a, b) =>a[0] - b[0]);

Comments

0
const arr = [
  [745, 4],
  [643, 2],
  [123, 3],
  [643, 5],
];

arr.sort((a, b) => {
  for (let i = 0; i < a.length && i < b.length; i++) {
    if (a[i] === b[i]) {
      // these elements are equal, move to next element
    } else {
      // these elements are not equal so compare them
      return (a[i] + "").localeCompare(b[i] + "", undefined, {
        numeric: true,
      });
    }
  }
  return 0; // since nothing was returned, both arrays are deeply equal
}); // sort array of variable length arrays alphabetically

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.