如何在Javascript中按字母顺序对此数组进行排序?

时间:2017-06-20 20:27:33

标签: javascript arrays sorting

所以我有这个数组:

[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [3, "Half-Eaten Apple"],[7, "Toothpaste"]];

我想根据第二个元素按字母顺序对该数组的元素进行排序。所以我想这样订购:

[[21," Bowling Ball"],[2," Dirty Sock"],[1,"发夹"],[3,& #34;半吃Apple"],[5," Microphone"]],[7," Toothpaste"];

我可以在javascript中完成此操作吗?

2 个答案:

答案 0 :(得分:4)

使用正确的数组并使用第二项,您可以使用Array#sort提示Sorting non-ASCII characters String#localeCompare来比较字符串。



var array = [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];

array.sort(function (a, b) {
    return a[1].localeCompare(b[1]);
});

console.log(array);




答案 1 :(得分:0)

let stuff = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [1, "Hair Pin"],
  [5, "Microphone"],
  [3, "Half-Eaten Apple"],
  [7, "Toothpaste"]];

这可以通过使用String.prototype.localeCompare()方法按字母顺序对项目进行排序来轻松完成。

stuff.sort((item1, item2) => item1[1].localeCompare(item2[1]));