0

I am studying javasript and trying to write a small program to find a sum of an element in some arrays. For example, they gave us some arrays like this

[
  { name: 'shoe', amount: 100 },
  { name: 't shirt', amount: 200 },
  { name: 'hat', amount: 400 }
]

expect is 700

I must use array reduce method to solve this problem. Could you please give me some ideas for this problem?

Thank you very much for your time.

secan
  • 2,622
  • 1
  • 7
  • 24
  • 2
    Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+reduce+sum+array+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Oct 29 '21 at 08:59
  • https://stackoverflow.com/questions/5732043/how-to-call-reduce-on-an-array-of-objects-to-sum-their-properties – Tom Oct 29 '21 at 08:59
  • You need to have a proper array too. Here is a reduce: `[{ name : "shoe", amount : 100 }, { name : "t shirt", amount : 200}, { name : "hat", amount : 400 }].reduce((acc,{amount}) => { acc+=amount; return acc},0)` – mplungjan Oct 29 '21 at 09:05

1 Answers1

-1
const sum = array.reduce((acc, item) => {
    acc+= item.amount;
    return acc;
}, 0);
munleashed
  • 1,677
  • 1
  • 3
  • 9
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 29 '21 at 18:16