[英]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: 我想按照每个内部数组中的第二个元素按字母顺序排序这个arr
,即:
[
[600, 'bar'],
[700, 'Baz'],
[500, 'Foo'],
]
Note the case insensitivity. 注意不区分大小写。 Also, I would love to use lodash helpers if they come in handy here! 此外,如果他们派上用场,我很乐意使用lodash助手!
Here is a concrete, working example, using Array.prototype.sort
: 这是一个使用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);
Array.prototype.sort takes a function which will be applied to each pair of items in the array. Array.prototype.sort接受一个函数,该函数将应用于数组中的每对项目。 The return of that function determines how the items are sorted (it needs to return a positive number, 0, or a negative number). 该函数的返回确定项目的排序方式(它需要返回正数,0或负数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.