2

I have been breaking my brain for the last 2 days trying to find a solution to the problem but I can't figure it out.

I need to sort an array of arrays first numerically and then lexicographically. While a custom a < b function can solve the first, a normal array.sort() can do the second. But I have no clue how to combine them.

I have an array similar to this one:

var arr = [
    [ '80', '1', '230' ],
    [ '9', '1', '230' ],
    [ 'Ken', '6', '100' ],
    [ 'Dan', '2', '800' ],
    [ 'Tom', '6', '500' ],
    [ 'team10', '2', '222' ],
    [ 'team9', '2', '222' ]
  ];

This array needs to be sorted numerically first according to the numbers in arr[n][1] (largest to smallest). Results with the same arr[n][1] value need to them be ordered numerically according to arr[n][2] (largest to smallest). And finally results with the same value [n][1] and [n][2] need to be ordered lexigographically based on arr[n][0].

The farthest I have gotten so far is this approach:

function sortArr() {
       arr.sort(function(a,b) {
          if (a[1] === b[1]) {
              if (a[2] === b[2]) {
                  return b[0] < a[0];
              }
              return a[2]-b[2];
          }
          return b[1]-a[1]
      });
  }

While the numerical sorting works with this, the lexicographical sorting doesn't. Any help would be appreciated.

0

1 Answer 1

1

I suggest to use a chained approach with String#localeCompare for strings.

Sort order:

  • at index 1 desc
  • at index 2 desc
  • at index 0
    • not nummerical part asc
    • nummerical part asc

var arr = [[ '80', '1', '230' ], [ '9', '1', '230' ], [ 'Ken', '6', '100' ], [ 'Dan', '2', '800' ], [ 'Tom', '6', '500' ], [ 'team10', '2', '222' ], [ 'team9', '2', '222' ]];

arr.sort(function (a, b) {
    var aa = a[0].split(/(\d+)/g),
        bb = b[0].split(/(\d+)/g);

    return b[1] - a[1] ||
        b[2] - a[2] ||
        aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});

console.log(arr);

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

2 Comments

Thank you Nina. Same issue. If you swap team10 and team9 in the original array and run your code, they will not be sorted correctly.
This is because 1 < 9 you have to parse the numbers and compare them then instead of per character compare

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.