在Javascript中对字符串值排序数组数组

时间:2016-05-12 10:14:58

标签: javascript arrays sorting multidimensional-array lodash

我想在字符串长度上对数组进行排序,如下所示

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?

我还没有找到重复的问题。有人能找到吗?请注意,我要求的排序是数组数组而不是对象数组。

1 个答案:

答案 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"]]