如何基于 assetCode
比较/合并两个数组。
这是代码:
list.component.ts
data = [
{
code: "Machine 1",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-18 00:00:00"
},
{
code: "Machine 1",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-19 00:00:00"
},
{
code: "Machine 2",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-20 00:00:00"
},
{
code: "Machine 3",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-21 00:00:00"
},
{
code: "Machine 4",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-22 00:00:00"
},
{
code: "Machine 5",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-23 00:00:00"
}
];
result = [];
constructor() {
this.result = this.setData(this.data);
}
setData(paramsArr: Array<any>): Array<any> {
let newData1 = [];
paramsArr.forEach(x => {
const existing = newData1.find((y: any) => format(y.date, 'YYYY-MM') === format(x.date, 'YYYY-MM')
&& y.assetCode === x.assetCode && y.code === x.code);
if (existing) {
existing.assetCount += existing.assetCount;
} else {
newData1.push(x);
}
});
let newData2 = [];
newData1.forEach(x => {
if (newData2.filter((y: any) => y.assetCode === x.assetCode).length <= 0) {
newData2.push(
{
assetCode: x.assetCode,
date: x.date
}
);
}
});
return newData1;
}
如果这个
assetCode
等于 assetCode
那么它会像这样显示最佳答案
这是减少的一个很好的用例
data = [
{
code: "Machine 1",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-18 00:00:00"
},
{
code: "Machine 1",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-19 00:00:00"
},
{
code: "Machine 2",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-20 00:00:00"
},
{
code: "Machine 3",
assetCode: "PRN",
assetCount: 1,
date: "2019-01-21 00:00:00"
},
{
code: "Machine 4",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-22 00:00:00"
},
{
code: "Machine 5",
assetCode: "PRN 1",
assetCount: 3,
date: "2019-01-23 00:00:00"
}
];
const merge = array => array.reduce((results, item) => {
const data = results.find(i => i.code === item.code);
if (data) {
data.assets[item.assetCode] = (data.assets[item.assetCode] || 0) + item.assetCount;
} else {
results.push({
code: item.code,
assets: { [item.assetCode]: item.assetCount }
});
}
return results;
}, []);
console.log(merge(data));
关于javascript - 如何以 Angular 比较/合并两个数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59080867/