So, I’m using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.
For instance, example 1…
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 67, 34, 99, 56, 89
This would return true
…example 2:
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 67, 99, 56, 89
This would return false
…example 3:
Array A contains the following values
34, 78, 89
Array B contains the following values
78, 89
This would return false
So far I have tried to solve this by:
- Extending Jquery with a custom ‘compare’ method to compare the two arrays. Problem is this only returns true when the arrays are identical and as you can see from example 1 I want it to return true even if they aren’t identical but at least contain the value
- using Jquerys .inArray function, but this only checks for one value in an array, not multiple.
Any light that anyone could throw on this would be great.
Advertisement
Answer
JavaScript
x
11
11
1
function containsAll(needles, haystack){
2
for(var i = 0; i < needles.length; i++){
3
if($.inArray(needles[i], haystack) == -1) return false;
4
}
5
return true;
6
}
7
8
containsAll([34, 78, 89], [78, 67, 34, 99, 56, 89]); // true
9
containsAll([34, 78, 89], [78, 67, 99, 56, 89]); // false
10
containsAll([34, 78, 89], [78, 89]); // false
11