Issue
I have this array
Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}]
I want to get this Arr = [{ code: "code1", id: "14", count: 61}]
Note: all fields in the objects I want to combine are same except count which is the field I want to sum.
Solution
You can do it like this:
// create new array that will keep your new objects:
var newArray = [];
// iterate over objects in original array:
this.originalArray.forEach((item) => {
// create new object that you *might* push into new array;
// use 'id' property of the current item in iteration:
var newItem = { id: item.id, code: null, count: 0 };
// iterate again over original array's objects to compare
// each of them with the current item from upper iteration:
this.originalArray.forEach((innerItem, i) => {
// check if they have the same id:
if (innerItem.id == item.id) {
// if they do, set values of a new object by adding
// the count values
newItem.count = newItem.count + innerItem.count;
// and setting the code to be the same as in item from upper iteration
newItem.code = item.code;
}
});
// push new object to new array only if the new array doesn't already have
// an item with that id:
if (!newArray.some((x) => x.id == newItem.id)) newArray.push(newItem);
});
console.log(newArray);
I guess you can have any number of items with the same id in your array, so this works for that too.
STackblitz example: https://stackblitz.com/edit/angular-ivy-1hkspy
Answered By - Misha Mashina
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.