Reputation: 477
I've used help from previous posts to get so far, but I just can't get this to work. I want to test if ALL group2 array elements exist in the group1 array. At the moment I'm getting opposite results to what I want. I've tried reversing the code in the 'compare arrays' jQuery section, but no luck. Example outcomes are given below in columns. https://jsfiddle.net/v82pfx2w/. Can anyone shed light on this?
group1: group1: group1:
Luxembourg Greece Greece
Netherlands Netherlands Netherlands
Belgium Luxembourg Luxembourg
Belgium Belgium
group2
Netherlands group2 group2
Greece Netherlands Luxembourg
Luxembourg Luxembourg Belgium
Belgium Belgium
NO MATCH YES MATCH YES MATCH
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
<div id="containerStore">
<div class='AggregCountriesBNLUX'>
<label>Netherlands</label>
<label>Greece</label>
<label>Luxembourg</label>
<label>Belgium</label>
</div>
<div class='AggregCountriesWEur'>
<label>Netherlands</label>
<label>Luxembourg</label>
<label>Belgium</label>
</div>
<div class='AggregCountriesWEur'>
<label>Luxembourg</label>
<label>Belgium</label>
</div>
</div>
var group1 = [];
group1 = ['Luxembourg', 'Netherlands', 'Belgium']
$('#containerStore div[class^="AggregCountries"]').each(function(i, obj) {
group2 = $(this).map(function() {
return $.trim($(this).text());
})
.get();
group2 = group2.join();
// compare arrays:
var compareGroups = group1.every(function(val) {
return group2.indexOf(val) >= 0;
})
alert(compareGroups);
});
Upvotes: 0
Views: 26
Reputation: 35222
You can use every
var hasAll = group2.every(function(val) {
return group1.indexOf(val) >= 0;
});
Updated fiddle:
In your fiddle, you were not getting each label's text to separate index of group2
. I have added find('label')
which will return a collection. Also, you were doing group2 = group2.join();
which replaced the array with a string.
Upvotes: 1