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

帅比萌擦擦* 提交于 2019-12-17 16:59:28

问题


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!


回答1:


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);



回答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).



来源:https://stackoverflow.com/questions/39583327/javascript-sort-array-of-arrays-by-second-element-in-each-inner-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!