在javascript中添加对象数组中的重复项

时间:2017-07-17 12:58:51

标签: javascript

我有一个包含对象数组的对象。这些数据有重复的年份。

data = {{value:"1", year:2000},{value:"3", year:2000},{value:"5", year:2010},{value:"2", year:2000},{value:"4", year:2010}};

我想添加重复年份的值并创建新的obj,它应该是这样的。

data1 = {{value:"6", year:2000},{value:"9", year:2010}};

2 个答案:

答案 0 :(得分:2)

如果它真的是一个数组,就像这样:

data = [{value:"1", year:2000},{value:"3", year:2000},{value:"5", year:2010},{value:"2", year:2000},{value:"4", year:2010}];

然后简单

var result = data.reduce(function(result,{value,year}){
  (result.find(el=>el.year===year)||(result[result.length]={year,value:0})).value+=+value;
  return result;
},[]);

http://jsbin.com/nozesofoqe/1/edit?console

或者使用哈希表:

var result = [],hash={};
data.forEach(function({value,year}){
  (hash[year]||(hash[year]=result[result.length]={year,value:0})).value+=+value;
},[]);

http://jsbin.com/pehobajete/edit?console

注意:上面的代码使用ES6,它只适用于现代浏览器......

答案 1 :(得分:0)

检查这是否有效

var inputArray=[{value:1, year:2000},{value:3, year:2000},{value:5, year:2010},{value:2, year:2000},{value:4, year:2010}];
var groups = {};
for (var i = 0; i < inputArray.length; i++) 
{
  var groupName = inputArray[i].year;
  if (!groups[groupName]) 
  {
    groups[groupName] = 0;
  }
  groups[groupName] = groups[groupName] + inputArray[i].value;
}
var outputArray = [];
for (var groupName in groups) 
{
  outputArray.push({year: groupName, value: groups[groupName]});
}
console.log(outputArray);

https://jsfiddle.net/zprzw4qp/2/