DEV Community

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

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.