Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  51] [ 3]  / answers: 1 / hits: 161947  / 13 Years ago, thu, february 9, 2012, 12:00:00

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:




  1. 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

  2. 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.


More From » jquery

 Answers
22
function containsAll(needles, haystack){ 
for(var i = 0; i < needles.length; i++){
if($.inArray(needles[i], haystack) == -1) return false;
}
return true;
}

containsAll([34, 78, 89], [78, 67, 34, 99, 56, 89]); // true
containsAll([34, 78, 89], [78, 67, 99, 56, 89]); // false
containsAll([34, 78, 89], [78, 89]); // false

[#87578] Tuesday, February 7, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;