本文介绍了按字符串对包含数组的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多个数组的数组,我想根据这些数组中的某个字符串对数组进行排序.
I have an array that contains several arrays and I would like to order the arrays based on a certain string within those arrays.
var myArray = [
[1, 'alfred', '...'],
[23, 'berta', '...'],
[2, 'zimmermann', '...'],
[4, 'albert', '...'],
];
如何按名称排序,使 albert 排在最前面,zimmermann 排在最后?
How can I sort it by the name so that albert comes first and zimmermann comes last?
如果我可以使用整数进行排序,我知道该怎么做,但字符串让我一无所知.
I know how I would do it if I could use the integer for sorting but the string leaves me clueless.
感谢您的帮助!:)
推荐答案
这可以通过将支持函数作为参数传递给 Array.sort
方法调用来实现.
This can be achieved by passing a supporting function as an argument to the Array.sort
method call.
像这样:
function Comparator(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
var myArray = [
[1, 'alfred', '...'],
[23, 'berta', '...'],
[2, 'zimmermann', '...'],
[4, 'albert', '...'],
];
myArray = myArray.sort(Comparator);
console.log(myArray);
这篇关于按字符串对包含数组的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!