gpt4 book ai didi

javascript - 如何以 Angular 比较/合并两个数组

转载 作者:行者123 更新时间:2023-12-05 01:15:48 25 4
gpt4 key购买 nike

如何根据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 那么它会像这样显示 enter image description here

最佳答案

这是 reduce 的一个很好的用例

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com