我有两个对象数组,我需要匹配其中一个数组的顺序。这是一个例子:
const outOfOrderArray = [{field: 'foo'}, {field: 'bar'}, {field: 'bazz'}, {field: 'bizz'}];
const arrayInProperOrder = [{field: 'bizz'}, {field: 'bazz'}, {field: 'foo'}, {field: 'bar'}];
如何使outOfOrderArray
与arrayInProperOrder
中的对象顺序相匹配?
答案 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);

答案 2 :(得分:0)
您可以使用array.prototype.sort
和array.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);