Home > Software engineering >  How to return from a function with an array loop and nested forEach loop?
How to return from a function with an array loop and nested forEach loop?

Time:12-19

I have a function with nested loops, first is an array loop and inside a forEach loop.

const myFunction = (data: string[][]): boolean => {

  for (const row of data) {
    row.forEach((item, i) => {

      if (!something) {
        return false;
      }
      if (
        !somethingelse
      ) {
        return false;
      }

      return undefined;
    });
  }

  return true;
};

Whenever I return false I would like that myFunction will return false, and only at the end if false wasn't returned, I'd like to return true. However to my understanding since it's nested loops, When I return false, I'm actually breaking out of the loop.

The only solution I thought about is to declare a variable and set it to "false" and then return the result at the end of all loops. However I'm finding that this might not be a good solution since es-lint complains when trying to change variables declared outside of the loop (can cause memory leaks). Is there another way without creating a variable, is there a way to return from a function without solely break out of the loop?

CodePudding user response:

I think for this you could use the .some method on arrays.

const myFunction = (data: string[][]): boolean => {
    const result = data.some(row => 
        row.some((item, i) => {
            if(!something) 
                return false
            else if (!somethingElse)
                return false
            else return true 
      }))
    
    return result
}

This would allow you to iterate through all of the data, if one of the conditions is met to true then the value of result would be true. Else it would be false.

CodePudding user response:

A "for(;;)" loop or a "for of" are options which don't take away your ability to return early.

Another option is to use "find" to return a specific value from the array, or "some" if you only need to return true/false.

CodePudding user response:

Well, you can't break a forEach loop.

So you have to use either a plain for loop, or another for-of for your inner loop.

  • Related