javascript - 根据值对javascript对象数组进行排序

时间:2015-08-25 15:35:52

标签: javascript arrays sorting

我有一个像这样的对象数组:

{"aid":1,"id":51,"modifier":5},
{"aid":2,"id":51,"modifier":5},
{"aid":3,"id":51,"modifier":2},
{"aid":4,"id":51,"modifier":3},
{"aid":5,"id":51,"modifier":3}

我将添加一个对象{"aid":6,"id":51,"modifier":5},现在数组将如下所示:

{"aid":1,"id":51,"modifier":5},
{"aid":2,"id":51,"modifier":5},
{"aid":3,"id":51,"modifier":2},
{"aid":4,"id":51,"modifier":3},
{"aid":5,"id":51,"modifier":3},
{"aid":6,"id":51,"modifier":5}

但我想知道我是如何将新对象{"aid":6,"id":51,"modifier":5}推入数组的最后一个索引,而是基于modifier,如下所示:

{"aid":1,"id":51,"modifier":5},
{"aid":2,"id":51,"modifier":5},
{"aid":6,"id":51,"modifier":5}
{"aid":3,"id":51,"modifier":2},
{"aid":4,"id":51,"modifier":3},
{"aid":5,"id":51,"modifier":3},

我不知道是否有可能,somebdy可以解决这个问题。感谢

2 个答案:

答案 0 :(得分:2)

您可以将自定义比较函数传递给Array.sort e.g

list.sort(function (a, b) {
  if (a.modifier > b.modifier) {
    return 1;
  }
  return -1;
});

我不确定您的搜索顺序背后的逻辑是什么,但如果您可以编写比较函数,则可以按它排序。

答案 1 :(得分:0)

我注意到您的对象似乎按修饰符援助进行排序。这意味着您要按多个属性排序。写一个像这样的比较器

function comparator(keys, a, b) {
    var k, key, mod = [1, -1], order;
    for (k = 0; k < keys.length; ++k) {
        key = keys[k].key;
        order = !keys[k].descending;
        if (b[key] > a[key]) return order ? -1 : 1;
        else if (b[key] < a[key]) return  order ? 1 : -1;
    }
    return 0;
}

现在说你的数组被称为foo.bind当你将密钥权重传递给foo.sort

时,你的密钥权重
foo.sort(
    comparator.bind(null, [
        {key: 'modifier', descending: true},
        {key: 'aid'},
    ])
);