I have an array of objects like below for example.
{name: \"Mc Donald\", quantity: 4, maleCount: 1, femaleCount: 0}
{name: \"KFC\", quantity: 9, maleCou
My solution based on reduce:
let data = [
{name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1}
];
// We will only keep an array of values of the merged object
let result = Object.values(
// Merge data to name indexed objects
data.reduce((p,c) => {
// Ensure key (name) exists
if (!p[c.name]) {
// If first occurence, duplicate object (to avoid modification of original array)
p[c.name] = Object.assign({}, c);
} else {
// If key (name) already exists, sum up relevant attributes
p[c.name].quantity += c.quantity;
p[c.name].maleCount += c.maleCount;
p[c.name].femaleCount += c.femaleCount;
}
// return updated object
return p;
}, {})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
hope this will help
check this code below:
var array = [
{name: "Mc Donald", quantity: 4, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "Mc Donald", quantity: 4, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 1, femaleCount: 0},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
{name: "KFC", quantity: 9, maleCount: 0, femaleCount: 1},
];
var result = [];
for(var index in array){
var obj = array[index];
if(result.hasOwnProperty(obj.name)) {
result[obj.name].quantity += obj.quantity;
result[obj.name].maleCount += obj.maleCount;
result[obj.name].femaleCount += obj.femaleCount;
}else{
result[obj.name] = {};
result[obj.name].quantity = obj.quantity;
result[obj.name].maleCount = obj.maleCount;
result[obj.name].femaleCount = obj.femaleCount;
}
}
console.log(result);