合并两个数组并按日期求和



我有两个数组,我想合并这两个数组并按日期求和

以下是阵列的示例

const lz = [
{
date: "2020-05",
value: 100
},
{
date: "2020-06",
value: 200
}
]
const sp = [
{
date: "2020-05",
value: 150
},
{
date: "2020-06",
value: 250
}
]

结果应该是两个阵列的总和

const data = [
{ date: "2020-05", value: 250 },
{ date: "2020-06", value: 450 }
]

您可以先将两个数组展开为一个,然后将其缩小为

const lz = [
{
date: "2020-05",
value: 100
},
{
date: "2020-06",
value: 200
}
]
const sp = [
{
date: "2020-05",
value: 150
},
{
date: "2020-06",
value: 250
}
]
function merge(arr1,arr2){
return [...arr1, ...arr2].reduce((a,v) => {
let index = a.findIndex(({date}) => date === v.date);
if(index !== -1) {
a[index].value += v.value;
return a;
}
return [...a, { date:v.date, value: v.value }]
},[])
}
console.log(merge(sp, lz))

最新更新