Home > Mobile >  return the first index with forEach
return the first index with forEach

Time:01-18

I have an array of monsters. monster is an object for example

{
type: "FIRE",
name: "Sosa",
original: true,
food: ["meet","egg"] // cannot contains 2 identical food
}

what I want is to return the index of the first monster having an X food I have tried this function:

let x = "meet";
let index = -1;
let i = -1;
animals.forEach((animal) => {
  i  ;
  animal.food.forEach((food) => {
    if (food === "x") index = i;
  });
});
return index;

this is not working for all cases. I am new to programming please some explications and help I will be thankfull

CodePudding user response:

your code is returning the index of the last found item not the first. so it works only when the last found item is at the same time the first found ie only one item is found.

if you really want to use forEach an alternative is to store all found indexes :

var foundIndexes = [];

// your code 
if(food === x) foundIndexes.push(i);
//your code

const myIndex = foundIndexes.length == 0 ?  -1 : foundIndexes[0] // that means if the array is still empty myIndex = -1 else myIndex = the first element of foundIndexes ie the first found index
return myIndex;

you can also use array.findIndex it does exactly what you are looking for or even array.every to stop the loop once you find the first item

CodePudding user response:

You can use Array#findIndex in conjunction with Array#includes.

let idx = animals.findIndex(a => a.food.includes('x'));
  • Related