regniscire
regniscire

Reputation: 117

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. 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 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. :)

Upvotes: 9

Views: 1423

Answers (1)

timolawl
timolawl

Reputation: 5564

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;

Upvotes: 17

Related Questions