How do I return from forEach while leaving the hugging method?

I want to iterate with forEach

and when the correct element was found return the value. It seemed to me that the simple return

inside forEach

would be enough, but I found out that the result was in the calling expression undefined

.

So, I had to declare an output variable covered by the entire method and tag all elements, even though the correct one was already found. (Items are unique.)

getMenuIndex(url) {
  let output = -1;

  this.menus.forEach(app => {
    app.subs.forEach(sub => {
      console.log(sub.link + " vs " + url);
      if (sub.link === url)
        // return sub.id;
        output = sub.id;
    });
  });

  return output;
}

      

This code smell is long. Is there an easier way to select the ID of the item that matches the URL condition?

+3


source to share


2 answers


Fortunately, we have for..of

TypeScript and ES6 for scenarios like this:

getMenuIndex(url) {
  for (const app of this.menus) {
    for (const sub of app.subs) {
      console.log(sub.link + " vs " + url);
      if (sub.link === url)
        return sub.id;
    }
  }

  return -1;
}

      



This is very useful in cases where constraints are obvious forEach

, such as await

/ yield

or return

/ break

.

As the other answers say, there are array methods that are better suited for the case. Although for TypeScript, the ES5 target for..of

translates to normal for

and is thus the fastest solution as such.

+5


source


You can use Array#some

and exit with true

.



function getMenuIndex(url) {
    let output = -1;
    this.menus.some(app => app.subs.some(sub => {
        if (sub.link === url) {
            output = sub.id;
            return true;
        }
    }));
    return output;
}

      

+1


source







All Articles