Вы можете reduce
массив object
, имеющий month
как key
и num
как value
, затем map
Object.entries
до нужного массива:
const arr = [
{ num: 5000, month: "September" },
{ num: 6000, month: "September" },
{ num: 4500, month: "August" },
{ num: 3500, month: "August" },
{ num: 5000, month: "jan" },
{ num: 6000, month: "feb" }
];
const reduced = arr.reduce((acc, { num, month }) => {
acc[month] = (acc[month] || 0) + num;
return acc;
}, {});
const result = Object.entries(reduced).map(([month, num]) => ({ num, month }));
console.log(result);
или reduce
непосредственно к нужному массиву:
const arr = [
{ num: 5000, month: "September" },
{ num: 6000, month: "September" },
{ num: 4500, month: "August" },
{ num: 3500, month: "August" },
{ num: 5000, month: "jan" },
{ num: 6000, month: "feb" }
];
const result2 = arr.reduce((acc, curr) => {
const ndx = acc.findIndex(e => e.month === curr.month);
if (ndx > -1) {
acc[ndx].num += curr.num;
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result2)