1

I need to sort out element in a nested array.

In each nest array there is 1 string and 1 integer.

var arr1 = [["2000", 2], ["11", 2], ["11", 2], ["10003", 4], ["22", 4], ["123", 6], ["1234000", 10], ["44444444", 32], ["9999", 36]]

I need to sort out the array by ascending integer (not the string). Which I can do by doing this:

var res = arr1.sort(function(a, b) {
    return a[1] - b[1];
});

However, when 2 integers have the same value, I need to sort them by their string (only for the matching integers, not for the rest of the array).

The result should be:

[["11", 2], ["11", 2], ["2000", 2], ["10003", 4], ["22", 4], ["123", 6], ["1234000", 10], ["44444444", 32], ["9999", 36]]

I can't figure how to make this happen. I tried a for loop but keep getting an error.

Anyone to help me on this?

Thanks!

  • 1
    The [best answer](https://stackoverflow.com/a/46256174/5260024) at the dupe is actually not the most upper one ... TLDR: `return a[1] - b[1] || a[0] - b[0]` – Jonas Wilms Mar 14 '19 at 21:43

1 Answers1

1

You could extend the sort by sorting with the first index.

BTW, Array#sort, sort the array in situ, that means the array mutates the order of the items.

var array = [["2000", 2], ["11", 2], ["11", 2], ["10003", 4], ["22", 4]] ;

array.sort(function(a, b) {
    return a[1] - b[1] || a[0].localeCompare(b[0]);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392