我正在尝试对其中包含字符串数组的数组进行排序。它类似于这个问题 ( Sort an array with arrays in it by string ) 但我不确定如何实现它。我的数组如下
var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];
我试图按名称或内部数组的第二个参数按字母顺序(不区分大小写)对其进行排序。之后,如果有两个元素具有相同的第二个参数,我想按第一个参数排序。我尝试使用以下但没有成功,也没有真正明白为什么。任何人都可以建议:
function Comparator(a,b){
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];
myArray = myArray.sort(Comparator);
要在第二个参数之后对第一个参数进行排序,我会这样做吗?
function Comparator(a,b){
if (a[1] < b[1]){
if (a[2] < b[2]) return -1
if (a[2] > b[2]) return 1;
}
return -1;
}
if (a[1] > b[1]) return 1;{
if (a[2] < b[2]) return -1
if (a[2] > b[2]) return 1;
}
return 1;
}
return 0;
}
var myArray = [
['blala', 'alfred', '...'],
['jfkdj', 'berta', '...'],
['vkvkv', 'zimmermann', '...'],
['cdefe', 'albert', '...'],
];
myArray = myArray.sort(Comparator);
最佳答案
你可以编码:
function Comparator(a, b) {
// you can use the `String.prototype.toLowerCase()` method
// if the comparison should be case insensitive
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
}
上述函数首先根据数组的第二个元素对元素进行排序。如果第二个元素相等,则根据第一个元素对它们进行排序,如果 a[1] === b[1]
和 a[0] === b[0]
它返回 0
,这使 a
和 b
位置保持不变。
From MDN Array.prototype.sort
documentation :
If
compareFunction
is supplied, the array elements are sorted according to the return value of the compare function. Ifa
andb
are two elements being compared, then:
- If
compareFunction(a, b)
is less than0
, sorta
to a lower index thanb
, i.e.a
comes first.- If
compareFunction(a, b)
returns0
, leavea
andb
unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.- If
compareFunction(a, b)
is greater than0
, sortb
to a lower index thana
.compareFunction(a, b)
must always return the same value when given a specific pair of elementsa
andb
as its two arguments. If inconsistent results are returned then the sort order is undefined.
关于javascript - 对其中包含字符串的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930010/