Bobby Burner
Bobby Burner

Reputation: 9

How to create multiple booleans in a javascript function/loop?

I have this piece of code:

function restrictListProducts(prods, restriction) {
    let product_names = [];
    for (let i=0; i<prods.length; i+=1) {
        if ((restriction == "Vegetarian") && (prods[i].vegetarian == true)) {
            product_names.push(prods[i].name);
        }
        else if ((restriction == "GlutenFree") && (prods[i].glutenFree == true)){
            product_names.push(prods[i].name);
        }
        else if (restriction == "None"){
            product_names.push(prods[i].name);
        }
    }
    return product_names;
}

The user inputs their dietary restrictions and are presented with a list of available food. The user is also asked if they want their food to be organic. How should I modify this function so it takes into account foods that are organic given that all current categories (vegetarian, GF, etc) can be organic and non-organic.

The products are organized like this:

var products = [
    {
        name: "brocoli",
        vegetarian: true,
        glutenFree: true,
        organic: true,
        price: 1.99
    },

Upvotes: 1

Views: 131

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386746

Why not use restrictions as an array of same named strings like their corresponding keys of the products.

For none take nothing, because Array#every returns true for empty arrays.

selection = products.filter(product => restrictions.every(k => product[k]));

const products = [{
    name: "broccoli",
    vegetarian: true,
    glutenFree: true,
    organic: true,
    price: 1.99
  },
  {
    name: "matso",
    vegetarian: true,
    glutenFree: true,
    organic: false,
    price: 1.99
  }
]



const getSelection = (products, restrictions) => {
  return products.filter(product => restrictions.every(k => product[k]));
};

console.log(getSelection(products,["vegetarian","organic"]))
console.log(getSelection(products,["vegetarian","glutenFree"]))

Upvotes: 3

Related Questions