Check if an array contains any element of another array in JavaScript

后端 未结 26 1524
礼貌的吻别
礼貌的吻别 2020-11-22 08:48

I have a target array [\"apple\",\"banana\",\"orange\"], and I want to check if other arrays contain any one of the target array elements.

For example:

26条回答
  •  心在旅途
    2020-11-22 08:51

    I wrote 3 solutions. Essentially they do the same. They return true as soon as they get true. I wrote the 3 solutions just for showing 3 different way to do things. Now, it depends what you like more. You can use performance.now() to check the performance of one solution or the other. In my solutions I'm also checking which array is the biggest and which one is the smallest to make the operations more efficient.

    The 3rd solution may not be the cutest but is efficient. I decided to add it because in some coding interviews you are not allowed to use built-in methods.

    Lastly, sure...we can come up with a solution with 2 NESTED for loops (the brute force way) but you want to avoid that because the time complexity is bad O(n^2).

    Note:

    instead of using .includes() like some other people did, you can use .indexOf(). if you do just check if the value is bigger than 0. If the value doesn't exist will give you -1. if it does exist, it will give you greater than 0.

    indexOf() vs includes()

    Which one has better performance? indexOf() for a little bit, but includes is more readable in my opinion.

    If I'm not mistaken .includes() and indexOf() use loops behind the scene, so you will be at O(n^2) when using them with .some().

    USING loop

     const compareArraysWithIncludes = (arr1, arr2) => {
         const [smallArray, bigArray] =
            arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
    
         for (let i = 0; i < smallArray.length; i++) {
           return bigArray.includes(smallArray[i]);
         }
    
          return false;
        };
    

    USING .some()

    const compareArraysWithSome = (arr1, arr2) => {
      const [smallArray, bigArray] =
        arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
      return smallArray.some(c => bigArray.includes(c));
    };
    

    USING MAPS Time complexity O(2n)=>O(n)

    const compararArraysUsingObjs = (arr1, arr2) => {
      const map = {};
    
      const [smallArray, bigArray] =
        arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
    
      for (let i = 0; i < smallArray.length; i++) {
        if (!map[smallArray[i]]) {
          map[smallArray[i]] = true;
        }
      }
    
      for (let i = 0; i < bigArray.length; i++) {
        if (map[bigArray[i]]) {
          return true;
        }
      }
    
      return false;
    };
    

    Code in my: stackblitz

    I'm not an expert in performance nor BigO so if something that I said is wrong let me know.

提交回复
热议问题