0

I am kinda new with javascript and was wondering if anyone can help me with a simple problem. I have an array that has both strings and integers, but I need to get the price and sum them all up with a button click. can anyone help me with this one?

var toys = [
  {
    name: "Lego",
    price: 15.6,
  },
  {
    name: "Master of the Universe",
    price: "28.3",
  },
  {
    name: "Barbie",
    price: null,
  },
  {
    name: "Mr Potato Head",
    price: 89.99,
  }
]
  • Hi, the process of going through the array to get the numbers is covered here: https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties Do you have another question beyond that? – MBer Mar 21 '21 at 20:51
  • Hi Bryan, Welcome to Stackoverflow. Please take the [tour](https://stackoverflow.com/tour) (and get a badge). Your question lacks any attempt at solving this problem on your own. The idea is for you to try to get something to work and then come here with specific problems you are unable to resolve. Taking the tour and reading about [How to ask a good question](https://stackoverflow.com/help/how-to-ask) in the help center will provide all the information you need. – Randy Casburn Mar 21 '21 at 20:54

2 Answers2

0
toys.map(el => +el.price).reduce((a,b) => a+b)

This should do. The plus sign converts strings to number if it's a number in a string form. Null is also converted to 0 in this case.

A side note, don't use var. Always use const or let.

İlker
  • 1,872
  • 1
  • 12
  • 28
0

I need to get the price and sum them all up with a button click.

Create a button and eventlistener for that button button.addEventListener('click', calculatePrice()), when clicked pass a function that maps each value returning the reduced values of the toys => currentValue.price as a number. Number() converts the null and sting values to a number so you can add them together as numbers.

const toys = [{
    name: "Lego",
    price: 15.6,
  },
  {
    name: "Master of the Universe",
    price: "28.3",
  },
  {
    name: "Barbie",
    price: null,
  },
  {
    name: "Mr Potato Head",
    price: 89.99,
  }
]
// get the button element by id
const calc = document.getElementById('calc')
// variable to output calculated price on button click
const output = document.getElementById('output')
// function that will calculate prices of toys
const calculatePrice = () => {
  return toys
    // map the values of the current-value of toys array
    // toy.price as a Number()
    .map(toy => Number(toy.price))
    // add each toys price using the reduce method
    .reduce((eachtoy, price) => eachtoy + price)
}

// event listener on click that will output the function
// as text using el.textContent = calculatePrice()
calc.addEventListener('click', (e) => output.textContent = calculatePrice())
<button id="calc">Calculate Price of Toys</button>
<div id="output"><div>
dale landry
  • 7,831
  • 2
  • 16
  • 28