George Foreman
George Foreman

Reputation: 419

Sort 2d array by first element in JavaScript

I have a 2d array like so:

myArray = [ [20,6], [12,6], [17,6], [2,6], [11,5], [18,5], [7,4], [4,4] ];

I wish to sort it by first index values - [2,6] should come before [12,6], [16,6]... [4,4] before [7,4] in that order... to obtain:

sortedArray = [ [2,6], [12,6], [17,6], [20,6], [11,5], [18,5], [4,4], [7,4] ];

Upvotes: 1

Views: 871

Answers (3)

code-eat-sleep
code-eat-sleep

Reputation: 11

You can provide sort with a comparison function.

myArray.sort(function(x,y){
    return x[0] - y[0];
});

Here's the reference for sort function - sort()

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386660

You need to respect the sorting of the second item of each array:

  1. sort by index 1 descending,
  2. sort by index 0 ascending.

const array = [[20, 6], [12, 6], [17, 6], [2, 6], [11, 5], [18, 5], [7, 4], [4, 4]];

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

console.log(JSON.stringify(array));

Upvotes: 3

xMayank
xMayank

Reputation: 1995

You can sort by the first element like this.

const myArray = [ [20,6], [12,6], [17,6], [2,6], [11,5], [18,5], [7,4], [4,4] ];

let ans = myArray.sort( (a, b) => {
  return a[0] - b[0]
})

console.log(ans)

Upvotes: 0

Related Questions