Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Sort array of arrays by second element in each inner array

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!

like image 888
Danny Delott Avatar asked Sep 19 '16 23:09

Danny Delott


Video Answer


1 Answers

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);
like image 182
qxz Avatar answered Oct 27 '22 07:10

qxz