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. :)
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With