Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 553
regniscire Avatar asked May 02 '16 19:05

regniscire


People also ask

How do you check if all elements in an array are in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if all elements in an array are in another array Python?

Use numpy. isin() to find the elements of a array belongs to another array or not. it returns a boolean array matching the shape of other array where elements are to be searched. numpy.

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.


1 Answers

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;
like image 171
timolawl Avatar answered Oct 12 '22 00:10

timolawl