-3

How can I sort 2D array with JavaScript?

I want to be able to sort the first column and then after sort the second column, but without change the first sorted column.

I have:

arr = [[3, 2], 
       [1, 2],
       [2, 2],
       [2, 1],
       [2, 3]]

I expect:

arr = [[1, 2], 
       [2, 1],
       [2, 2],
       [2, 3],
       [3, 2]]

Thanks in advance!

5
  • Just sort the first column and then when you have to swap elements you swap both column elements? Commented Jul 5, 2018 at 18:21
  • Use an ordering function that first compares the first elements. If they're equal, it compares the second elements. Commented Jul 5, 2018 at 18:22
  • Can I have a code example ? Commented Jul 5, 2018 at 18:23
  • The most intuitive way is: Transpose the array, sort the arrays of the new object using the Array sort function, and transpose it back, I cannot add the code since they marked your question as duplicated. Commented Jul 5, 2018 at 19:59
  • This is the fiddle, it prints to the console, change it to print the new array anyway you wish - jsfiddle.net/oL4ctufd/11 Commented Jul 5, 2018 at 20:16

1 Answer 1

0

Try the following:

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.