简体   繁体   中英

Sorting nested Array inside Array using sort

I want to sort nested array (array inside an array) ie 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] ...

All you need for the callback is a[0] - b[0] || a[1] - b[1] 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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM