Maraecia Washington
Maraecia Washington

Reputation: 59

Looping over array contents to compare values

I thought I was doing everything right but I can't figure out why my code keeps returning false. When called with (inventory, and string) all I get is false although the values in varies.

Create a function called shouldWeOrderThisCandy that takes in the inventory array a specific type of candy (string).

Return true if the number inStock is less than the weeklyAverage, otherwise, return false.

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

How do I return true?

Upvotes: 1

Views: 371

Answers (4)

tarkh
tarkh

Reputation: 2549

Yo have some errors in your code and you returning from loop immediately after first cycle, while you need to investigate each candy, if I get it right... Check code below, read comments

UPD: added method to specify only one candy

const 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 }
]
          
const shouldWeOrderThisCandy = (inventory, str) => {
  // Set some object to store all DB values results
  const result = {};
  // Loop
  for(let i = 0; i < inventory.length; i++) {
    // If str exist, then skip everything else
    if(str && str !== inventory[i].candy) continue;
    // If in stock more then weekly avarage - do not order
    if(inventory[i].weeklyAverage < inventory[i].inStock) result[inventory[i].candy] = false;
    // If in stock less then weekly avarage - order
    else result[inventory[i].candy] = true;
  }
  // Return formed object
  return result;
}

// Log one element
console.log('Only one candy:');
console.log(shouldWeOrderThisCandy(inventory, "Twizzlers"));

// Log all
console.log('All candies:');
console.log(shouldWeOrderThisCandy(inventory));

Upvotes: 0

Dr. Rahul Jha
Dr. Rahul Jha

Reputation: 1064

I see a problem in your code. Inventory is a list and you are accessing property using inventory.yourproperty which is incorrect. instead use like this and you should get correct result.

if (inventory[i].weeklyAverage < inventory[i].inStock){
 return true;  

I tested and verified this code using C# language.

Edited:

Adding sample code here using C#

Model:

class Invenory
{
    public string candy;
    public int inStock;
    public int weeklyAverage;

}

Method:

void shouldWeOrderThisCandy()
    {
        List<Invenory> inventories = new List<Invenory>() 
                                        { new Invenory { candy= "Twizzlers", inStock= 180, weeklyAverage= 200},
                                        new Invenory { candy= "Sour Patch Kids", inStock= 90, weeklyAverage= 100},
                                        new Invenory { candy= "Milk Duds", inStock= 300, weeklyAverage= 170},
                                        new Invenory { candy= "Now and Laters", inStock= 150, weeklyAverage= 40} };

        foreach (var inventory in inventories)
        {
            if (inventory.weeklyAverage < inventory.inStock)
            {
                //write logic to add order
            }
        }
    }

Upvotes: 0

Winky
Winky

Reputation: 506

I'm not sure your meaning, and I add a new column to store the result of every row.

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 row = inventory.find(item => item.candy === candy);
    if (row.weeklyAverage < row.inStock) {
        return true;
    } else {
        return false;
    }
  }
  
  console.log(shouldWeOrderThisCandy(inventory, 'Milk Duds'));

Upvotes: 1

David Losert
David Losert

Reputation: 4802

Hey there and welcome to StackOverflow! :)

The first problem here is that you never read the current object from the inventory-Array in your For-Loop, but you always try to access weeklyAverage on the array itself - which does not have this property. :)

Therefore, your if condition results in a comparison undefined < undefined.

This can be fixed by pulling out the value like so:

function shouldWeOrderThisCandy(inventory, []){
  for (i = 0; i < inventory.length; i++){
    const currentCandy = inventory[i];
    if (currentCandy.weeklyAverage < currentCandy.inStock){
      return true;  
    } else {
     return false;
    }
  } 
};

However, this will always just check the first candy in your array and then immidiately return from the function, thus canceling your for-loop.

Not quite sure if you want that loop to check every candy or just one specific. But if you need the status for all Candy, you should not return in the for-loop, but save the values in an object, for example like this:

function shouldWeOrderThisCandy(inventory, []){
  const candyNeedsOrderMap = {};
  for (i = 0; i < inventory.length; i++){
    const currentCandy = inventory[i];
    let needsOrder = false;
    if (currentCandy.weeklyAverage < currentCandy.inStock){
      needsOrder = true;  
    } 
   candyNeedsOrderMap[currentCandy.candy] = result
  } 
  return candyNeedsOrderMap;
};

However, if you need the value for one specific candy, you could achieve it like this:

function shouldWeOrderThisCandy(inventory, candyName){
  const candy = inventory.find(current => current.candy === candyName);
  return candy.weeklyAverage < candy.inStock;
};

Upvotes: 0

Related Questions