5

I have an array that looks like this:

const arr = [
  [500, 'Foo'],
  [600, 'bar'],
  [700, 'Baz'],
];

I would like to sort this arr alphabetically by the second element in each inner array, ie:

[
  [600, 'bar'],
  [700, 'Baz'],
  [500, 'Foo'],
]

Note the case insensitivity. Also, I would love to use lodash helpers if they come in handy here!

Danny Delott
  • 6,756
  • 3
  • 33
  • 57

2 Answers2

9

Here is a concrete, working example, using Array.prototype.sort:

const arr = [
  [500, 'Foo'],
  [600, 'bar'],
  [700, 'Baz']
];

arr.sort((a,b) => a[1].toUpperCase().localeCompare(b[1].toUpperCase()));

console.log(arr);
qxz
  • 3,814
  • 1
  • 14
  • 29
2

Array.prototype.sort takes a function which will be applied to each pair of items in the array. The return of that function determines how the items are sorted (it needs to return a positive number, 0, or a negative number).

jlogan
  • 947
  • 6
  • 9