Merge Objects With The Same Id But Sum Values Of The Objects
I want to reduce my array of objects by comparing previous and current object from the array, if the id of previous object is different then current object, then I write the previo
Solution 1:
You can use thisArg
parameter in forEach
loop and pass a empty object to store values.
var data = [{"Clicks":210,"Company":"A","_id":{"CompanyID":5}},{"Clicks":35,"Company":"C","_id":{"CompanyID":3}},{"Clicks":15,"Company":"B","_id":{"CompanyID":2}},{"Clicks":13,"Company":"A","_id":{"CompanyID":5}}];
var result = [];
data.forEach(function(obj) {
var id = obj._id.CompanyIDif(!this[id]) result.push(this[id] = obj);
elsethis[id].Clicks += obj.Clicks;
}, Object.create(null));
console.log(result);
Solution 2:
For a version with Array#reduce
, you could use a hash table as reference to the same company with a closure over the hash table.
var data = [{ Clicks: 210, Company: "A", _id: { CompanyID: 5 } }, { Clicks: 35, Company: "C", _id: { CompanyID: 3 } }, { Clicks: 15, Company: "B", _id: { CompanyID: 2 } }, { Clicks: 13, Company: "A", _id: { CompanyID: 5 } }],
result = data.reduce(function (hash) {
returnfunction (r, a) {
var key = a._id.CompanyID;
if (!hash[key]) {
hash[key] = { Clicks: 0, Company: a.Company, _id: a._id };
r.push(hash[key]);
}
hash[key].Clicks += a.Clicks;
return r;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "Merge Objects With The Same Id But Sum Values Of The Objects"