7

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
3
  • 4
    your objects in your array are invalid. Also, what have you tried so far and what issues are you facing? Commented Jun 13, 2020 at 10:22
  • Yes, every object has a key-value pair Commented Jun 13, 2020 at 10:24
  • reduce() executes a function on each element of the array, resulting in single output value. Commented Jun 13, 2020 at 18:07

3 Answers 3

14

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

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

Comments

9

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

Comments

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

2 Comments

well why using map you can reduce and add like this data.reduce((a, b) => a + b.prix,0)
Separating map and reduce is more modular and doesn't require the initializer (0). It's also easier to refactor into a transducer or other functions with subsets/supersets of this functionality.

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.