3

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.

Sasha
  • 113
  • 1
  • 6
  • 1
    Does this answer your question? [How to sort 2 dimensional array by column value?](https://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value) – Mady Daby Apr 19 '21 at 19:35
  • 1
    Not really, but the answers have already been given below, thanks to everyone for the help, I will go to sort out the sort options. – Sasha Apr 19 '21 at 19:42
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+sort+array+of+arrays+with+two+number+elements) of [Sort an array of arrays in JavaScript](https://stackoverflow.com/q/50415200/4642212). Or, in general, [How to sort an array of objects by multiple fields?](https://stackoverflow.com/q/6913512/4642212). – Sebastian Simon Apr 19 '21 at 19:51
  • @Sasha _“Not really”_ — Yes it does, because it’s all exactly the same idiomatic pattern: `.sort((value1, value2) =>` _⟨expression⟩_ `)`, where _⟨expression⟩_ is an `||` chain of `value1[numProperty] - value2[numProperty]` or `value1[strProperty].localeCompare(value2[strProperty])` (both ascending), or their negation (descending). In your case, you have numeric properties, and you want to sort by index `0`, then by index `1`, both ascending, so _⟨expression⟩_ becomes `value1[0] - value2[0] || value1[1] - value2[1]`. Adding destructuring or other fancy syntax doesn’t change the basic pattern. – Sebastian Simon Apr 19 '21 at 20:01

3 Answers3

4

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]));
entithat
  • 324
  • 6
  • 18
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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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];
});
Mureinik
  • 297,002
  • 52
  • 306
  • 350