Search code examples
javascriptarraysreactjsecmascript-6sum

React JS Get Sum of Numbers in Array


I have this array

const data = [
  {"One",prix:100},
  {"Two",prix:200},
  {"Three",prix:300}
]

and I want to get the sum of all those prix like this:

sum = 600

Solution

  • You can use the reduce :

    data.reduce((a,v) =>  a = a + v.prix , 0 )
    

    const data = [
      {title : "One",prix:100},
      {title : "Two",prix:200},
      {title : "Three",prix:300}
    ]
    
    console.log((data.reduce((a,v) =>  a = a + v.prix , 0 )))