我有一个带有示例值的对象数组
[
{name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},
{name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},
{name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},
{name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},
]
我想在optimalValue
和realValue
中的日期和总和相同的数组元素中找到类似的数组:
[
{date:"2018-08-01", optimalValue:"56", realValue:"77"},
{date:"2018-08-03", optimalValue:"17", realValue:"23"},
{date:"2018-08-04", optimalValue:"12", realValue:"11"},
]
答案 0 :(得分:1)
只需使用哈希表即可查找/分组重复项:
const hash = {}, result = [];
for(const { date, name, optimalValue, realValue } of input) {
if(!hash[date])
result.push(hash[date] = { date, name, optimalValue: 0, realValue: 0 });
hash[date].realValue +=+ realValue;
hash[date].optimalValue +=+ optimalValue;
}
答案 1 :(得分:0)
您可以使用函数reduce
进行分组和求和,然后使用函数Object.values
提取所需的数组。
let array = [{name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},{name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},{name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},{name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},],
result = Object.values(array.reduce((a, {name, date, optimalValue, realValue}) => {
a[date] = (a[date] || {date, optimalValue: 0, realValue: 0});
a[date].realValue = String(Number(a[date].realValue) + Number(realValue));
a[date].optimalValue = String(Number(a[date].optimalValue) + Number(optimalValue));
return a;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
您可以使用Array.reduce()
。由于您需要optimalValue
和realValue
作为字符串类型,因此可以在使用parseInt()
将值求和后将它们转换为字符串:
var arr = [
{name:"Name1",date:"2018-08-01", optimalValue:"33", realValue:"55"},
{name:"Name2",date:"2018-08-03", optimalValue:"17", realValue:"23"},
{name:"Name3",date:"2018-08-01", optimalValue:"23", realValue:"12"},
{name:"Name4",date:"2018-08-04", optimalValue:"12", realValue:"11"},
];
var res = arr.reduce((acc, obj)=>{
var existObj = acc.find(item => item.date === obj.date);
if(existObj){
existObj.realValue = (parseInt(existObj.realValue) + parseInt(obj.realValue)).toString();
existObj.optimalValue = (parseInt(existObj.optimalValue) + parseInt(obj.optimalValue)).toString();
return acc;
}
acc.push(obj);
return acc;
},[]);
console.log(res);