Check if one array is contained in another array

I have

['a', 'b', 'c']

      

I want to know if this array is contained in this array:

['a', 'b', 'c', 'd']

      

I know I can do 2 for loops and check item by item, but is there one for it?

+4


source to share


2 answers


You can do this using Array.prototype.some

. This will run the provided function against all elements in the array and return true if the function returns true for any of them. The following will return true if any of the elements from are array

not contained in otherArray

, which you can use to determine if one array is completely contained in another:

return !array.some(function(item) {
   return otherArray.indexOf(item) === -1;
});

      

However, this is not the most elegant solution. The logic can be summed up as:

no elements from array not in another array

It has too many negatives. Instead, we can use Array.prototype.every

which is very similar, except that it only returns true if all of the array elements return true for the provided function. Below is what we had before:

return array.every(function(item) {
   return otherArray.indexOf(item) !== -1;
});

      

Except that can be summed up as:



all elements of an array in another array

Finally, we can implement this as an additional prototype feature. Note that the second parameter for every

is optional, and sets what it this

means in the function provided. If we don't pass it, we won't be able to link to this

from outside.

Array.prototype.contains = function(array) {
    return array.every(function(item) {
        return this.indexOf(item) !== -1;
    }, this);
}

      

Now this code can be used as one liner in our code:

['a', 'b', 'c'].contains(['a', 'b']) // returns true

      

If you can use ECMAScipt 6 you can use arrow functions to make this a true one-liner.

return array.every(item => otherArray.indexOf(item) !== -1);

      

+12


source


ES6 one line answer

containedArray.every(element => mainArray.includes(element))

      



... an improved answer in addition to @James Brierley's ES6 suggestion: using each (...) (which returns true

if all elements pass the test we provided - otherwise false

) along with including includes

, which IMO is more readable and less prone to errors than verification index !== -1

.

var mainArray = [1, 30, 39, 29, 10, 13];

var containedArray = [1, 30, 39, 29]

console.log(containedArray.every(element => mainArray.includes(element)));

      

0


source







All Articles