0

I am trying to get the foodId based on the names of food in the selected array. I have a filter to find the foods and then a map to get the ids, but the filter seems to be skipping the first item in the selected array. See snippet:

var response = {
  "status": "success",
  "data": {
    "foodsCount": 20,
    "foodIds": [
      {
        "foodId": "574",
        "food": "French Fries"
      },
      {
        "foodId": "722",
        "food": "Hamburgers"
      },
      {
        "foodId": "1736",
        "food": "Pad See Ew"
      },
      {
        "foodId": "1737",
        "food": "Pasta"
      },
      {
        "foodId": "1739",
        "food": "Pho noodles"
      },
      {
        "foodId": "1740",
        "food": "Tacos"
      },
      {
        "foodId": "1741",
        "food": "Falafels"
      },
      {
        "foodId": "1742",
        "food": "Burrito"
      },
      {
        "foodId": "1743",
        "food": "Hotdogs"
      }
    ]
  }
}
const selected = ["Hamburgers", "Hotdogs"];
// should return [722, 1743]
const foodList = response.data.foodIds
const foundFoods = foodList.filter(isInArray)
const foundIds = foundFoods.map(x => parseInt(x.foodId))

console.log('foundIds', foundIds);

function isInArray(item) {
  return selected.indexOf(item.food) > 0
}

I can keep adding items into the selected array and it will work but the first item in selected always returns false in the isInArray function. Does anyone know why this only happens to the first item? Thanks!

2
  • arrays are zero based not 1 based Commented Oct 26, 2017 at 16:17
  • make this selected.indexOf(item.food) > 0 to selected.indexOf(item.food) >= 0 Commented Oct 26, 2017 at 16:19

1 Answer 1

1

isInArray should be like this:

function isInArray(item) {
  return selected.indexOf(item.food) >= 0
}
Sign up to request clarification or add additional context in comments.

Comments

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.