简体   繁体   中英

Sum of array, fetched data from database

I used json to send prices over. How do i sum all the numbers in this array?

 arr[i].itemPrice

I have tried this but i am only getting the second value and not the total

for (var i =0; i<arr.length;i++){
sum += arr[i].itemPrice;
alert(sum);
}

You can use the Array's reduce function (ES6):

const sum = arr.reduce((acc, el) => acc + el.itemPrice, 0);

The reduce function allows you to iterate over a collection and accumulate the elements data however you'd like.

Use the following :

for (var i = 0; i < arr.length; i++) {
   sum += arr[i].itemPrice;
}
alert(sum);

Alert the sum after the loop completes.

Looks like your array is something like below , you can use Array.reduce for this

 let arr = [{ itemPrice: 1}, { itemPrice: 2}, { itemPrice: 3}] console.log(arr.reduce((a, {itemPrice}) => a + itemPrice, 0)) 

Use Array#reduce

 const data = [{itemPrice:20.00}, {itemPrice:15.00}, {itemPrice:25.00}]; const total = data.reduce((sum, {itemPrice})=>sum+itemPrice, 0); console.log(total); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM