ferrelnm
ferrelnm

Reputation: 1

Why is everything returning true in function javascript?

The question is: Create a function that checks if we need to order more candy. If the inStock is less than the weeklyAverage, return true; otherwise, return false. No matter what I do to this function, however, I can't get it to return properly. It returns true (correctly) for the for the first two candies, but also returns true for the last two, when they should be false. Any suggestions? Thank you!

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(x, i) {
  for (let i = 0; i < x.length; i++) {
    if (x[i].inStock < x[i].weeklyAverage) {
      return true;
    }else {
      return false;
    }
    }
  }

Upvotes: 0

Views: 80

Answers (2)

Kristen
Kristen

Reputation: 11

For anyone still looking at this, you don't need the else conditional.

put:

return inventory[i].inStock < inventory[i].weeklyAverage

inside the if body, and it will return either true or false for every iteration of the loop.

Upvotes: 1

Kishor Patil
Kishor Patil

Reputation: 950

Try this to get list of candies to order.

var shouldWeOrderThisCandy1 =() => inventory.filter(candyIn=> candyIn.inStock < candyIn.weeklyAverage).reduce((acc,candyIn) => { acc.push(candyIn.candy); return acc; },[]);
shouldWeOrderThisCandy1();

Upvotes: 0

Related Questions