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!