mzaxhmars
mzaxhmars

Reputation: 95

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

Upvotes: 7

Views: 43463

Answers (3)

Majid Savalanpour
Majid Savalanpour

Reputation: 1823

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

arr.reduce(callback, initialValue);

reducer will only return one value and one value only hence the name reduce. Callback is a function to be run for each element in the array.

and Function arguments function(total,currentValue, index,arr):

Argument           Description

total              Required.The initialValue, or the previously returned value of the function
currentValue       Required.The value of the current element
currentIndex       Optional.The array index of the current element
arr                Optional.The array object the current element belongs to

in this example use this code:

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

const result = data.reduce((total, currentValue) => total = total + currentValue.prix,0);

console.log(result);  // 600

Upvotes: 9

Vivek Doshi
Vivek Doshi

Reputation: 58553

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 )))

Upvotes: 14

Nicky McCurdy
Nicky McCurdy

Reputation: 19554

const sum = data.map(datum => datum.prix).reduce((a, b) => a + b)

Upvotes: 3

Related Questions