我想在字符串长度上对数组进行排序,如下所示
var arr = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
var sortedArr = sortOnLengthOfString(arr);
>> sortedArr = [
[1951, "Mayfer"],
[1101, "Cetaphil"],
[1007, "Ferri Injection"],
[1785, "Actinac Capsules"]
]
Lodash最好有解决方案吗?或者简单的Javascript?
我还没有找到重复的问题。有人能找到吗?请注意,我要求的排序是数组数组而不是对象数组。
答案 0 :(得分:2)
您可以在此背景下使用Array#sort
,
var obj = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
obj.sort(function(a,b){
return a[1].length - b[1].length
});
console.log(obj);
//[[1951, "Mayfer"],[1101, "Cetaphil"],[1007, "Ferri Injection"],[1785, "Actinac Capsules"]]