Javascript按属性排序对象

时间:2017-05-17 05:16:51

标签: javascript arrays sorting

我有这样的数组。

var word_list = [
    {text: "Lorem", weight: 13},
    {text: "Ipsum", weight: 10},
    {text: "Dolor", weight: 9},
    {text: "Sit", weight: 8},
    {text: "Amet", weight: 6},
    {text: "Consectetur", weight: 5}
];

如何使用“text”或“weight”对其进行排序。

1 个答案:

答案 0 :(得分:3)

按文字排序:

word_list.sort(function (a, b) {
   return a.text.localeCompare(b.text);
});

按重量排序:

word_list.sort(function (a, b) {
   return a.weight - b.weight;
});