'sum duplicate array values and then storing them [react js]

I have an array that I want to write a function that get sum price of items that have same name like: jack=400 helen=200 and finally sort them

const data = [
  {name: jack,prix:100},
  {name:helen,prix:200},
  {name:jack,prix:300}
]


Solution 1:[1]

You can use Array.prototype.reduce() to get the desired output like below.

const data = [
  { name: "jack", prix: 100 },
  { name: "helen", prix: 200 },
  { name: "jack", prix: 300 },
];

const output = data.reduce((prev, { name, prix }) => {
  prev[name] = prev[name] ? prev[name] + prix : prix;
  return prev;
}, {});

console.log(output);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amila Senadheera