2 回答
TA贡献1788条经验 获得超4个赞
尝试减少第一个数组以仅获取不匹配的项目,而不是在开头合并数组:
const groupOrder = [{group_time_str: "25 Apr 2019",orders: [{vertical_id: "1",vertical_category: "A"},{vertical_id: "2",vertical_category: "B"}]},{group_time_str: "26 Apr 2019",orders: [{vertical_id: "1",vertical_category: "A"},{vertical_id: "2",vertical_category: "B"},{vertical_id: "3",vertical_category: "C"}]}];
const groupOrder2 = [{group_time_str: "26 Apr 2019",orders: [{vertical_id: "3",vertical_category: "C"},{vertical_id: "4",vertical_category: "D"}]},{group_time_str: "27 Apr 2019", orders: [{vertical_id: "1",vertical_category: "A"},{vertical_id: "2",vertical_category: "B"}]}];
const result = groupOrder.reduce((arr, g1) => {
const g2match = groupOrder2.find(
g2 => g2.group_time_str === g1.group_time_str
);
if (g2match) {
const orders = g1.orders.filter(
g1o =>
!g2match.orders.find(
m =>
g1o.vertical_id === m.vertical_id &&
g1o.vertical_category === m.vertical_category
)
);
g2match.orders = [...g2match.orders, ...orders];
return arr;
}
return [...arr, { ...g1 }];
}, []);
console.log([...result, ...groupOrder2]);
TA贡献1829条经验 获得超13个赞
您可以执行以下操作,过滤掉 cur.orders 以删除重复项,
var groupOrder = [
{
group_time_str: "25 Apr 2019",
orders: [
{
vertical_id: "1",
vertical_category: "A"
},
{
vertical_id: "2",
vertical_category: "B"
}
]
},
{
group_time_str: "26 Apr 2019",
orders: [
{
vertical_id: "1",
vertical_category: "A"
},
{
vertical_id: "2",
vertical_category: "B"
},
{
vertical_id: "3",
vertical_category: "C"
}
]
}
];
var groupOrder2 = [
{
group_time_str: "26 Apr 2019",
orders: [
{
vertical_id: "3",
vertical_category: "C"
},
{
vertical_id: "4",
vertical_category: "D"
}
]
},
{
group_time_str: "27 Apr 2019",
orders: [
{
vertical_id: "1",
vertical_category: "A"
},
{
vertical_id: "2",
vertical_category: "B"
}
]
}
];
const combine = [...groupOrder, ...groupOrder2];
const groupBy = combine.reduce((acc, cur) => {
acc[cur.group_time_str]
? (acc[cur.group_time_str].orders = [
...acc[cur.group_time_str].orders,
...cur.orders.filter(item => acc[cur.group_time_str].orders.findIndex(accOrder => item['vertical_id'] === accOrder['vertical_id'] && item['vertical_category'] === accOrder['vertical_category']) <= -1)
])
: (acc[cur.group_time_str] = cur);
return acc;
}, {});
console.log(groupBy);
body {
font-family: sans-serif;
}
<h1>Grouped Order</h1>
添加回答
举报