Skip to content
Advertisement

trouble multiplying in JavaScript

     1. let inventory = [
  { candy: "Twizzlers", inStock: 180, weeklyAverage: 200 },
  { candy: "Sour Patch Kids", inStock: 90, weeklyAverage: 100 },
  { candy: "Milk Duds", inStock: 300, weeklyAverage: 170 },
  { candy: "Now and Laters", inStock: 150, weeklyAverage: 40 }
];

// write the shouldWeOrderThisCandy function
function shouldWeOrderThisCandy(inventory){
  for (i = 0; i < inventory.length; i++)


if (inventory[i].inStock < inventory[i].weeklyAverage){ 
for (j = 0; j < inventory[i].weelyAverage.length; j++){
      return inventory[i].weeklyaverage[j] * 2;
   } else {
      return 0;
    }
  }
}

So what I am trying to do here in JavaScript is find out is i want to order more candy or not. So far I compare the in Stock to the weekly average and if in Stock is < weekly average I will order 2 times the weekly Average. However, if the is greater than in Stock then i will order nothing. Here’s my code so far. My function should take on 2 arguments which is inventory and candy here. I cant figure out why it returning nothing but zero, when it should be letting me know how much candy to order. please help example when called with “Twizzlers” it should return 400 since weekly Average for “Skittles” is 200 and 200 * 2 is 400 and so forth.

Advertisement

Answer

  1. You need to accept the item name as the second parameter.
  2. You can use Array#find to find the inventory item with the specified name.

let inventory = [
  { candy: "Twizzlers", inStock: 180, weeklyAverage: 200 },
  { candy: "Sour Patch Kids", inStock: 90, weeklyAverage: 100 },
  { candy: "Milk Duds", inStock: 300, weeklyAverage: 170 },
  { candy: "Now and Laters", inStock: 150, weeklyAverage: 40 }
];
function shouldWeOrderThisCandy(inventory, candy){
  const obj = inventory.find(x=>x.candy===candy);
  if(obj?.inStock < obj?.weeklyAverage) return obj.weeklyAverage * 2;
  else return 0;
}
console.log(shouldWeOrderThisCandy(inventory, "Twizzlers"));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement