Suppose, we have an array of objects like this −
const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }];
We are required to write a JavaScript function that takes in one such array.
The function should then merge all those objects together that have the common value for "id" property.
Therefore, for the above array, the output should look like −
const output = [{ "value": 10, "id": "111", "name": "BlackCat", "count": 2, }, { "value": 15, "id": "777", "name": "WhiteCat", "count": 1, }]
Example
const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }]; const combinedItems = (arr = []) => { const res = arr.reduce((acc, obj) => { let found = false; for (let i = 0; i < acc.length; i++) { if (acc[i].id === obj.id) { found = true; acc[i].count++; }; } if (!found) { obj.count = 1; acc.push(obj); } return acc; }, []); return res; } console.log(combinedItems(arr));
Output
And the output in the console will be −
[ { value: 10, id: '111', name: 'BlackCat', count: 2 }, { value: 15, id: '777', name: 'WhiteCat', count: 1 } ]