1

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.

3
  • 1
    you're returning after first iteration itself, i doubt you're getting 36 you must be getting 24 Commented Jul 20, 2019 at 18:45
  • also, you need to loop from zero to length-1 Commented Jul 20, 2019 at 18:46
  • Yes, sorry, I am getting 24 Commented Jul 20, 2019 at 18:49

3 Answers 3

1

You could skip the manual looping and use Array.reduce instead.

const total = cart.reduce((sum, item) => sum + item.itemPrice, 0);
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Yes, that's it! Thank you, I'm very new to coding and my brain is pretty fried right now from school!
Welcome to the world for coding :) If it works please mark it as the answer
0

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;
}

Comments

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.