Search code examples
javascriptarraysobject

Why do I keep getting false for some() javascript array method for an array inside an object?


const menu = [{
    name: "tofu fritters",
    ingredients: ["tofu", "egg yolk", "breadbrumbs", "paprika"],
  },
  {
    name: "black bean curry",
    ingredients: ["black beans", "garam masala", "rice"],
  },
  {
    name: "chocolate tiffin",
    ingredients: [
      "dark chocolate",
      "egg",
      "flour",
      "brown sugar",
      "vanilla essence",
    ],
  },
  {
    name: "hummus",
    ingredients: ["chickpeas", "tahini", "lemon", "garlic", "salt"],
  },
];

searchResult = menu.some(menuItem => menuItem.ingredients === 'flour');
console.log(searchResult);

I was expecting this to return true since flour is present in the array for the third menu item but it returns false. Some() only seems to return true if I remove the array entirely from the object.


Solution

  • As menuItem.ingredients is an array, try with menuItem.ingredients.includes('flour') instead of menuItem.ingredients === 'flour'

    The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

    const menu = [{
        name: "tofu fritters",
        ingredients: ["tofu", "egg yolk", "breadbrumbs", "paprika"],
      },
      {
        name: "black bean curry",
        ingredients: ["black beans", "garam masala", "rice"],
      },
      {
        name: "chocolate tiffin",
        ingredients: [
          "dark chocolate",
          "egg",
          "flour",
          "brown sugar",
          "vanilla essence",
        ],
      },
      {
        name: "hummus",
        ingredients: ["chickpeas", "tahini", "lemon", "garlic", "salt"],
      },
    ];
    
    searchResult = menu.some(menuItem => menuItem.ingredients.includes('flour'));
    console.log(searchResult);