-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!

  • Just sort the first column and then when you have to swap elements you swap both column elements? – chevybow Jul 05 '18 at 18:21
  • Use an ordering function that first compares the first elements. If they're equal, it compares the second elements. – Barmar Jul 05 '18 at 18:22
  • Can I have a code example ? – Marc-Antoine Jul 05 '18 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. – Daniel Jul 05 '18 at 19:59
  • This is the fiddle, it prints to the console, change it to print the new array anyway you wish - https://jsfiddle.net/oL4ctufd/11/ – Daniel Jul 05 '18 at 20:16

1 Answers1

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);
amrender singh
  • 7,949
  • 3
  • 22
  • 28