PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 16, 2022

[FIXED] How to .filter and .reduce javascript array object

 July 16, 2022     arrays, javascript, methods, web-deployment     No comments   

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 the shopCart variable and returns the total cost of both items as the total 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing