Reputation: 19
I have an array of objects (cart), the size of which can change, and I need to write a function to add the all the values of a key (itemPrice).
I have tried iterating through the array based on the array length with a for loop, but I don't know how to just add all of the values of that certain key together. I always end up just adding the first value to itself for the length of the array.
My array looks like :
[ { itemName: shoes, itemPrice: 12 }, { itemName: socks, itemPrice: 34 }, { itemName: shorts, itemPrice: 56 }
My for loop looks like:
function total() {
var total=0;
for (let i = 0; i <= cart.length; i++) {
total += cart[i]["itemPrice"] + cart[i]["itemPrice"];
return total;
}
}
I expect the output to be 102, but the total is 24. I know why it's 36, it's just adding the first itemPrice to itself 3 times, I just don't know how to get it to add the itemPrice values to each other.
EDIT: Yes, I meant I am getting 24, not 36.
Upvotes: 1
Views: 1578
Reputation: 1
Take a look at this, for example:
const cart = [{itemName: shoes, itemPrice: 12 }, { itemName: socks, itemPrice: 34 }, { itemName: shorts, itemPrice: 56 }];
const total = () => {
const checkProp = cart.prototype.map(e => return e.itemPrice).reduce((a, b) =>{return a + b;
}, 0);
return checkProp;
}
Upvotes: 0
Reputation: 4783
You could skip the manual looping and use Array.reduce instead.
const total = cart.reduce((sum, item) => sum + item.itemPrice, 0);
Upvotes: 1
Reputation: 323
Answer
var cart = [ { itemName: "shoes", itemPrice: 12 }, { itemName: "socks", itemPrice: 34 }, { itemName: "shorts", itemPrice: 56 }];
function total() {
var total=0;
for (let i = 0; i < cart.length; i++) {
total += cart[i]["itemPrice"] ;//+ cart[i]["itemPrice"];
// return total;// this is wrong it will exit the loop so you need to remove it
}
return total;
}
console.log(total());
Upvotes: 0