0

I want to sort nested array (array inside an array) i.e My array looks like this

const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]

To do that I wrote this logic

const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
    
    
     function sort (a,b) {
      if (a[0] < b[0]) return -1
      if (a[0] > b[0]) return 1
      if (a[0] === b[0]) {
        if (a.length > 1 && b.length > 1) {
          return sort(a.slice(0, 1), b.slice(0,1))
        }
        else return 0
      } 
    }

  console.log(input.sort((a,b) => {
    return sort(a,b)
  }))

but this is giving first element as [0,9] instead of [0, 6] and [2, 9] instead of [2,8] so on.

What I want is

  • Compare first element, if first element is equal, compare second ending elemennt

So [0, 6] should be before [0,9]...

1
  • to fix the code you wrote, you'd need return sort(a.slice(1, 2), b.slice(1,2)) Commented Oct 12, 2020 at 1:32

1 Answer 1

4

All you need for the callback is a[0] - b[0] || a[1] - b[1]:

const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))

If the array is of arbitrary length, then you do need a separate named function:

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

const input = [[3,9],[7,12],[3,8],[6,8],[9,10],[2,9],[0,9],[3,9],[0,6],[2,8]]
console.log(input.sort((a,b) => a[0] - b[0] || a[1] - b[1]))

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

2 Comments

Can you please explain this line of code a[0] - b[0] || a[1] - b[1] in input.sort((a,b) => a[0] - b[0] || a[1] - b[1])
It will return the difference if the first items in the arrays are different. Otherwise, if they're the same, it'll return the difference between the second items in the arrays.

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.