5

I'd like to sort a two dimensional array using javascript.

My array :

[
  ['1','6'],
  ['1','5'],
  ['2','3'],
  ['0','4'],
]

My sorting function :

// 1st sort
myArray.sort( function(a, b) {
  return a[0] - b[0];
});

// 2nd sort
myArray.sort( function(a, b) {
  return a[1] - b[1];
});

The result :

["2", "3"]
["0", "4"]
["1", "6"]
["1", "5"]

The result should be :

["0", "4"]
["1", "5"] // 5 before 6 and the left column is sorted
["1", "6"]
["2", "3"]
1

3 Answers 3

14

Your second sort is overriding the sorting done by first sort and it is only keeping the second column sorted.

You don't need two sort functions, just include both in a single sort as:

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

or without braces

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

Demo

var myArray = [
    ['1','6'],
    ['1','5'],
    ['2','3'],
    ['12','13'],
    ['0','4'],
];
myArray.sort((a, b) => (a[0] - b[0]) || (a[1] - b[1]));

console.log(myArray);

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

4 Comments

@NinaScholz Sure, I added braces initially for better readability
@NinaScholz the precedence between - and || isn't obvious (although it is documented), so braces can help
oh no. please do not use unary plusses for changing values to number because they are converted to number by using minus operator by default.
@NinaScholz You are right, I tested without unary plus and it worked as well. Thanks.
6

You could use a different approach for an arbitrary length of the arrays.

This solution assumes, that all inner arrays have the same length.

var array = [['1','6', '1'], ['1','5', '1'], ['1','5', '2'], ['2','3', '0'], ['0','4', '0']];

array.sort(function (a, b) {
    var d;
    a.some((v, i) => d = v - b[i]);
    return d;
});

console.log(array.map(a => a.join(' ')));

2 Comments

var i = 0, res; while(!(res = a[i] - b[i++])); return res; ... i still prefer imperative programming...
@JonasW., right, another possibility, but no length check. it loops forever with equal arrays, value wise.
4
 myArray.sort((a, b) => (a[0] - b[0]) || (a[1] - b[1]));

Just sort after the second slot if the first ones are equal

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.