0

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}
]

2
  • and what method you tried? Commented May 15, 2022 at 7:04
  • Does this answer your question? Get the Sum of Values in React JS Commented May 15, 2022 at 7:06

1 Answer 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.