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 )))
Answer from Vivek Doshi on Stack OverflowYou 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 )))
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
Displaying the Sum of values in React JSX
reactjs - How to calculate sum of object keys in array - javascript - Stack Overflow
getting the sum of a number in the array
reactjs calculate sum of all the value present in state in a form of array of object - Stack Overflow
Videos
Reduce is an array function, not a meal object function. Try replacing the forEach with the reduce.
meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0)
The first reduce assumes calories are numbers, the second is if strings
const meals = [
{ calorie: 10},
{ calorie: 15},
{ calorie: 20}
];
const calorieTotal = meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0);
console.log(calorieTotal); // 45 calories
const mealsAsStrings = [
{ calorie: '11'},
{ calorie: '12'},
{ calorie: '13'}
];
const calorieStringTotal = mealsAsStrings.reduce((totalCalories, meal) => totalCalories + parseInt(meal.calorie, 10), 0);
console.log(calorieStringTotal); // 36 calories
You can't use reduce method on array elements as it's an array method. In the example above you are looping into the array and trying to call reduce with each element of array which is not right. You can do as follows -
this.state.meals.reduce((accumulator, currentValue) => accumulator + currentValue)
Hope that helps.
UPDATE - As you are trying to calculate calories from meal object array, we can do it as follows -
this.state.meals.reduce((accumulator, currentValue)=> accumulator + accumulator, currentValue.calorie,0);
Check the link for detail use of reduce method - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can use Javascript's reduce function. This is basically the same as @epascarello answer but in ES6 syntax.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
const arr = [{level:2},{level:4},{level:5}];
const total = arr.reduce((prev,next) => prev + next.level,0);
console.log(total);
Either a simple loop
var a = [{level:1},{level:2},{level:3},{level:4}],
total = 0;
for (var i=0; i<a.length; i++) {
total += a[i].level;
}
console.log('total', total)
or reduce
var a = [{level:1},{level:2},{level:3},{level:4}]
console.log(a.reduce( function(cnt,o){ return cnt + o.level; }, 0))
const number = movies.map((movie) => movie.price);
const sum = number.reduce(function(a, b) {
return a + b;
}, 0);
I have 2 inputs one for the movie name and other for the price I'm trying to get the total price on the nav... I get the total price but when a add something it doubles the total number
this is the exercise I'm studying from
https://www.youtube.com/watch?v=35lXWvCuM8o
The , 0 should be the second argument to reduce, not in the return:
const total = props.numbers.reduce((prev, current) => {
return prev + current.num;
}, 0);
You need to provide an initial value for prev, as the second param of reduce. If its not provided then during the first run, first param of callback function is the first element of array and second param of callback function is the second element of array. Then the return value is passed to the first param and the next element is the second value.
So, to add I have added 0 as the initial value.
const numbers = [ { name: 'max', num: 3 }, { name: 'jack', num: 2 } ]
const total = numbers.reduce((prev, { num }) => {
return prev + num
}, 0)
console.log(total)
You should structure your data as an array of objects.
const exercises = [{ name: 'Fundamentals of React', exercise: 10 }, etc];
in render use
exercises.map(ex => <Content name={ex.name} exercises={ex.exercise}/>)
and for the sum use reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Here's my solution assuming you control data structure in App component
const Total = (props) => {
return (
<>
<p>props.totalExerciseCount</p>
</>
)
}
const App = () => {
const course: {
name: "Half Stack app development",
parts: [
{
title: "Fundamentals of React"
exerciseCount: 10
},
{
title: "Using props to pass data"
exerciseCount: 7
},
{
title: "State of a component"
exerciseCount: 14
},
]
}
let totalExerciseCount = 0;
return (
<div>
<Header name={course.name} />
{course.parts.map(part => {
totalExerciseCount += part.exerciseCount;
return <Content name={part.title} exercises={part.exerciseCount} />
})
}
<Total exercises={totalExerciseCount} />
</div>
)
}
I am using the map function to create a list. The list consists of objects that has a name and a number value.
At the end of the list, I want to show the total value of that list by adding up the number value from all the objects in the list.
I was about to create a function to do that. But then I thought that might be to redundant since I am already using the map function to iterate through the object.
Is it possible to do this within the map function or should I just make a different function/method to add up the total value?