在数组中查找具有相同日期和总和值的元素

时间:2018-07-11 13:26:11

标签: javascript arrays

我有一个带有示例值的对象数组

[
    {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"},
]

我想在optimalValuerealValue中的日期和总和相同的数组元素中找到类似的数组:

[
    {date:"2018-08-01", optimalValue:"56", realValue:"77"},
    {date:"2018-08-03", optimalValue:"17", realValue:"23"},
    {date:"2018-08-04", optimalValue:"12", realValue:"11"},
]

3 个答案:

答案 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()。由于您需要optimalValuerealValue作为字符串类型,因此可以在使用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);