Check if all elements can be found in another array

I need to check if all elements in an array can be found in another array. That is, I need to check if one array is a subset of another array.

Example:

var array = [1, 2, 5, 7]; var otherArray = [1, 2, 3, 4, 5, 6, 7, 8]; 

Comparing the two arrays above should return true, since all elements in the array can be found in otherArray .

 var array = [1, 2, 7, 9]; var otherArray = [1, 2, 3, 4, 5, 6, 7, 8]; 

Comparing the two arrays above should return false, since one of the elements in the array cannot be found in the otherArray .

I tried using the indexOf method inside a for loop without success. Hope someone can help me. :)

+6
source share
1 answer

Use Array.prototype.every :

The every () method checks whether all elements of the array passed the test implemented by the provided function.

 var array = [1, 2, 7, 9]; var otherArray = [1, 2, 3, 4, 5, 6, 7, 8]; var isSubset = array.every(function(val) { return otherArray.indexOf(val) >= 0; }) document.body.innerHTML = "Is array a subset of otherArray? " + isSubset; 
+11
source

All Articles