-5

I want to sort a list filled with lists by their 0th index.

In Python, this would look like

l = [[1, 0], [5, 1], [6, 2], [3, 2]

l.sort(key=lambda x: x[0])
#l is now [[1, 0], [3, 2], [5, 1], [6, 1]]

What would this look like in Javascript?

Lovesh Dongre
  • 1,294
  • 8
  • 23

2 Answers2

1

Array sort method does the same job:

const arr = [[1, 0], [5, 1], [6, 2], [3, 2]];
arr.sort((a,b) => a[0] - b[0]);
console.log(arr);
Jumshud
  • 1,385
  • 1
  • 13
  • 19
0

You could create a function which takes a function fro getting the value for sorting.

let l = [[1, 0], [5, 1], [6, 2], [3, 2]],
    fn = x => x[0],
    sort = fn => (a, b) => fn(a) - fn(b);

l.sort(sort(fn));
    
l.forEach(a => console.log(...a));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392