Issue
WebDev Student. I am having an issue with using .filter + .reduce
array methods and chaining to return the total cost of both items. Codeburst.io on the subject is super helpful but I need direction on how to apply to this specific exercise as I am targeting a property: value in the array.
This is an exercise in reducing the amount of code., so rather than using a for
loop to iterate through an array, I need to apply a method(s) to .filter through and .reduce to return the total cost of each item in the array. .price
Using the
shopCart
variable, create a function that takes theshopCart
variable and returns the total cost of both items as thetotal
variable. Add Code after "// code below".
var shopCart = [
{
id: 0,
name: 'Womens Shirt',
price: 30,
size: 'Small'
},
{
id: 1,
name: 'childs shirt',
price: 12,
size: 'Large'
}
]
function getCost(items){
let total = 0;
// code below
// code above
return total;
}
getCost(shopCart) < --- Add
let cost = getCost(shopCart); < ---OMIT
console.log(cost); < -- OMIT
PLease re-review - Code has been amended.
Solution
Here’s a more explicit approach.
function sum(nums) {
return nums.reduce((a, b) => a + b)
}
const prices = items.map(item => item.price)
const total = sum(prices)
Answered By - christo8989 Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.