在javascript中将顺序设置为对象数组

时间:2016-08-24 12:05:51

标签: javascript arrays sorting object

我需要找到一种最简单的方法来设置对象数组的顺序。 例如,有一个数组:

var array = [
    {id: 1, name: "Matt"},
    {id: 2, name: "Jack"},
    {id: 3, name: "Morgan"},
    {id: 4, name: "Bruce"}
];

我提供了

var order = [1,4,2,3];

指的是id项的对象array属性。

现在我需要重新排序数组,所以它应该是:

var array = [
    {id: 1, name: "Matt"},
    {id: 4, name: "Bruce"},
    {id: 2, name: "Jack"},
    {id: 3, name: "Morgan"}
]

3 个答案:

答案 0 :(得分:11)

使用 Array#sort 方法进行排序,并使用 Array#indexOf 方法在自定义排序函数中获取索引。

var array = [{
  id: 1,
  name: "Matt"
}, {
  id: 2,
  name: "Jack"
}, {
  id: 3,
  name: "Morgan"
}, {
  id: 4,
  name: "Bruce"
}];

var order = [1, 4, 2, 3];


array.sort(function(a, b) {
  // sort based on the index in order array
  return order.indexOf(a.id) - order.indexOf(b.id);
})

console.log(array);

答案 1 :(得分:1)

您还可以在reduce()数组上使用[1,4,2,3]返回对象,其中键将是元素,值将是每个元素的索引,然后按该对象排序。

var array = [
  {id: 1, name: "Matt"},
  {id: 2, name: "Jack"},
  {id: 3, name: "Morgan"},
  {id: 4, name: "Bruce"}
];

var s =  [1,4,2,3].reduce((r, e, i) => {return r[e] = i, r}, {});
var result = array.sort(function(a, b) {
  return s[a.id] - s[b.id];
});
console.log(result)

答案 2 :(得分:0)

我猜任何涉及排序的东西都不能比O(2n)解决方案更有效。所以我想做两个这样的工作减少如下;



var arr = [{id: 1, name: "Matt"}, {id: 2, name: "Jack"}, {id: 3, name: "Morgan"}, {id: 4, name: "Bruce"}],
  order = [1,4,2,3],
    lut = order.reduce((t,e,i) => (t[e] = i,t),{}),
 result = arr.reduce((res,obj) => (res[lut[obj.id]] = obj, res) ,[]);
 console.log(result);