0

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);
});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I'm getting an error 'group2.every is not a function'.
Ah, so cause was that I wasn't 'finding' the labels. Your help much appreciated!
@Silverburch yeah. It was creating an array of length one, with the texts of labels concatenated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.