regniscire regniscire - 7 months ago 12
Javascript Question

Check if all items can be found in another array

I need to check if all items in an array can be found within another array.
Example:

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


Comparing these two arrays above should return true as all items in
array
can be found in
otherArray
.

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


Comparing these two arrays above should return false as one of the items in
array
cannot be found in
otherArray
.

I have tried to use the indexOf method inside a for loop without success.
I hope someone could help me :)

Answer

Use Array.prototype.every:

The every() method tests whether all elements in the array pass 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;