1

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] ];
4
  • This is probably a duplicate but you can do it like this.. myArray.sort((a,b) => b[0] - a[0]) Commented Jun 28, 2020 at 7:19
  • @HalilÇakar That doesn't work. Commented Jun 28, 2020 at 7:21
  • 2
    If we sort it by first value as you mentioned, your expected output is wrong then. Commented Jun 28, 2020 at 7:22
  • @HalilÇakar a[0] - b[0] rather Commented Jun 28, 2020 at 7:24

3 Answers 3

3

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));

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

Comments

1

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()

Comments

0

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)

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.