I have a main array -
const arr = [
{ description: 'Senior', amount: 50 },
{ description: 'Senior', amount: 50 },
{ description: 'Adult', amount: 75 },
{ description: 'Adult', amount: 35 },
{ description: 'Infant', amount: 25 },
{ description: 'Senior', amount: 150 }
]
I want help with an es6 operation which will add the amount based on the key(description) and remove the duplicates.
Result array will somewhat look like -
const newArr = [
{ description: 'Senior', amount: 120 },
{ description: 'Adult', amount: 110 },
{ description: 'Infant', amount: 25 },
{ description: 'Senior', amount: 150 }
]
I have been using the reduce operator to achieve this using the solutions from below, but that removes the non-consecutive objects as well.
It would be really helpful if someone can help me with some es6 operators to perform the same operation.
const arr = [
{ description: "Senior", amount: 50 },
{ description: "Senior", amount: 50 },
{ description: "Adult", amount: 75 },
{ description: "Adult", amount: 35 },
{ description: "Infant", amount: 25 },
];
const result = Object.values(
arr.reduce((acc, item) => {
acc[item.description] = acc[item.description]
? { ...item, amount: item.amount + acc[item.description].amount }
: item;
return acc;
}, {})
);
console.log(result);
Array#reduce, iterate over the array while updating a Map where the key is the description and the value is the record with total amountMap#values, get the list of grouped objectsconst arr = [ { description: 'Senior', amount: 50 }, { description: 'Senior', amount: 50 }, { description: 'Adult', amount: 75 }, { description: 'Adult', amount: 35 }, { description: 'Infant', amount: 25 } ];
const res = [...
arr.reduce((map, current) => {
const { description } = current;
const grouped = map.get(description);
if(!grouped) {
map.set(description, { ...current });
} else {
map.set(description, { ...grouped, amount: grouped.amount + current.amount })
}
return map;
}, new Map)
.values()
];
console.log(res);
You may just use this snippet
array.filter((item, index) => array.indexOf(item) === index);
Refer to this link for more details. Or just copy this solution.