根据另一个对象数组的顺序对对象数组进行排序

时间:2018-05-11 14:03:34

标签: javascript

我有两个对象数组,我需要匹配其中一个数组的顺序。这是一个例子:

const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];

const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];

如何使outOfOrderArrayarrayInProperOrder中的对象顺序相匹配?

3 个答案:

答案 0 :(得分:2)

以下是如何在比@Faly的解决方案更少的循环中完成它。无需对数组进行排序。您可以循环遍历arrayInProperOrder并找到outOfOrderArray中的匹配元素,以便后者按顺序排列。

const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];
const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];

const newArray = [];

arrayInProperOrder.forEach(item => {
  const original = outOfOrderArray.find(i => i.field === item.field);

  if (original) {
    newArray.push(original);
  }
});

console.log(newArray);

如果您需要,只需将newArray分配给outOfOrderArray

答案 1 :(得分:1)

您可以创建一个临时对象来存储订单,并将其用作sort()

的基础

如果在临时对象上找不到某些字段,请使用Infinity作为默认值。



const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];

const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];

//Make a temp object - This will store the order of the field. This nessasary so that no need to search every reiteration on sort()
const tempObj = arrayInProperOrder.reduce((c, v, i) => Object.assign(c, {[v.field]: i + 1}), {});

//Sort the array.
outOfOrderArray.sort((a, b) => (tempObj[a.field] || Infinity) - (tempObj[b.field] || Infinity));

console.log(outOfOrderArray);




文档:sort()Infinity

答案 2 :(得分:0)

您可以使用array.prototype.sortarray.prototype.findIndex

const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];
const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];

outOfOrderArray.sort(
    (a, b) => arrayInProperOrder.findIndex(e => e.field === a.field) -  arrayInProperOrder.findIndex(e => e.field === b.field)
);

console.log(outOfOrderArray);

如果您关心性能,可以构建一个对象,允许您通过arrayInProperOrder数组中的字段值获取索引:

const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];
const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];
const indexes = arrayInProperOrder.reduce((m, o, i) => (m[o.field] = i, m), {});

outOfOrderArray.sort(
    (a, b) => indexes[a.field] -  indexes[b.field]
);

console.log(outOfOrderArray);