How to sort arrays by two elements of these arrays?

Viewed 121

I had an array of strings and I made an array of numbers. And now I have arrays with two elements. I want to sort them from smallest to largest on both elements:

What is now:

const numArray = array.map(str => parseInt(str))
console.log(numArray)
[15, 5]
[3, 55]
[25, 5]
[3, 10]
[15, 25]

I want to get:

[3, 10]
[3, 55]
[15, 5]
[15, 25]
[25, 5]

How can this be achieved? I think I need to use .reduce() or .sort(), but don't know how to do it right. I would be glad for any help.

3 Answers

The first we compare by first number a[0] - b[0]. And if we get the same a and b then we sort by the second number a[1] - b[1].

const arr = [
  [15, 5],
  [3, 55],
  [25, 5],
  [3, 10],
  [15, 25]
];

console.log(arr.sort((a, b) => a[0] - b[0] || a[1] - b[1]));

You could convert to string and use a natural sorting.

const array = [[15, 5], [3, 55], [25, 5], [3, 10], [15, 25]];

array.sort((a, b) => a.toString().localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));

array.forEach(a => console.log(...a));

You could create your own custom sorting function that compares the first element, and if the first element in two sub-arrays is equal, compares the second element:

numArray.sort((a,b) => {
    res = a[0] - b[0];
    if (res != 0) {
        return res;
    }
    return a[1] - b[1];
});
Related