1

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
    },
1
  • Remove the ifs.. Commented May 26, 2020 at 6:40

1 Answer 1

3

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"]))

Sign up to request clarification or add additional context in comments.

1 Comment

kudos @mplungjan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.