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

后端 未结 26 1093
礼貌的吻别
礼貌的吻别 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:49
    var target = ["apple","banana","orange"];
    var checkArray = ["apple","banana","pineapple"];
    
    var containsOneCommonItem = target.some(x => checkArray.some(y => y === x));`
    
    ["apple","grape"] //returns true;
    
    ["apple","banana","pineapple"] //returns true;
    
    ["grape", "pineapple"] //returns false;
    
    0 讨论(0)
  • 2020-11-22 08:51

    Using filter/indexOf:

    function containsAny(source,target)
    {
        var result = source.filter(function(item){ return target.indexOf(item) > -1});   
        return (result.length > 0);  
    }    
    
    
    //results
    
    var fruits = ["apple","banana","orange"];
    
    
    console.log(containsAny(fruits,["apple","grape"]));
    
    console.log(containsAny(fruits,["apple","banana","pineapple"]));
    
    console.log(containsAny(fruits,["grape", "pineapple"]));

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 08:53

    I came up with a solution in node using underscore js like this:

    var checkRole = _.intersection(['A','B'], ['A','B','C']);
    if(!_.isEmpty(checkRole)) { 
         next();
    }
    
    0 讨论(0)
  • 2020-11-22 08:55

    What about using a combination of some/findIndex and indexOf?

    So something like this:

    var array1 = ["apple","banana","orange"];
    var array2 = ["grape", "pineapple"];
    
    var found = array1.some(function(v) { return array2.indexOf(v) != -1; });
    

    To make it more readable you could add this functionality to the Array object itself.

    Array.prototype.indexOfAny = function (array) {
        return this.findIndex(function(v) { return array.indexOf(v) != -1; });
    }
    
    Array.prototype.containsAny = function (array) {
        return this.indexOfAny(array) != -1;
    }
    

    Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate

    0 讨论(0)
  • 2020-11-22 08:56

    I found this short and sweet syntax to match all or some elements between two arrays. For example

    // OR operation. find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE

    let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'b'];
    
    console.log(array2.some(ele => array1.includes(ele)));
    

    // prints TRUE

    // AND operation. find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE

    let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'x'];
    
    console.log(!array2.some(ele => !array1.includes(ele)));
    

    // prints FALSE

    Hope that helps someone in future!

    0 讨论(0)
提交回复
热议问题