Reputation: 419
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
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
Reputation: 386660
You need to respect the sorting of the second item of each array:
1
descending,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
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