DEV Community

Discussion on: The moment I realized forEach() does not return anything.

Collapse
 
mavarnare profile image
Miguel Varona

Hi! Hace you considered using the .includes() method? If not, can you tell me why? I'm kind of new to JS.

Thanks for your article!

Collapse
 
kaynguyen profile image
Kay N. • Edited

Hi Mike yes you totally can use includes() however it would make the function not algorithm-wise because you gotta nest one loop inside another:

const haveCommonItems = (array1, array2) => {
  for (i = 0; i < array1.length; i++) {
    if (array2.includes(array1[i])) {
      return true;
    }
  }
};

haveCommonItems(animals, pets); // returns "true"

So you nest includes() which loops thru array2 inside forEach(), which is not ideal in terms of time complexity if you have a huge amount of items in your arrays.