1

I have a set of multiple-choice questions that a user will answer via radio buttons. Depending on their choices, they will be presented with information relevant to said choices.

I'm using the map function to watch the form and capture the answers in an array:

$('input[type="radio"]').on('change', function() {
  var results = $('input[type="radio"]:checked').map(function() {
    return this.value;
  }).get();
});

This is working well but I am having trouble working out how to, once the answers have been input, to check if they match a predetermined array. Below is what I've tried with no success:

$('.subscription-builder input[type="radio"]').on('change', function() {
  var results = $('input[type="radio"]:checked').map(function() {
    return this.value;
  }).get();

  var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
  var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

  if (results == arrayTestOne) {
    console.log('WOOOO!');
  } else if (results == arrayTestTwo) {
    console.log('Hooray!');
  }

});

Any ideas?

2
  • Are you checking if elements are the same and in order? Commented Apr 3, 2018 at 8:29
  • @Eddie Yes on both accounts. Commented Apr 3, 2018 at 8:35

1 Answer 1

0

If you want to check if array is equal and on the same order, one option is you can .join(",") the array.

var results = ["Cheese", "Carrot", "Lettuce", "Apple"]; //TEMP CODE. 

var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

if (results.join(",") == arrayTestOne.join(",")) {
  console.log('WOOOO!');
} else if (results.join(",") == arrayTestTwo.join(",")) {
  console.log('Hooray!');
}

If You want to check even not in order, you can use every

var results = ["Cheese", "Apple", "Carrot", "Lettuce"]; //TEMP CODE. 

var arrayTestOne = ["Cheese", "Carrot", "Lettuce", "Apple"];
var arrayTestTwo = ["Banana", "Avocado", "Lettuce", "Pear"];

if (results.every(o => arrayTestOne.includes(o))) {
  console.log('WOOOO!');
} else if (results.every(o => arrayTestTwo.includes(o))) {
  console.log('Hooray!');
}

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

2 Comments

Perfect. Thanks so much for your help, @Eddie
Happy to help :)

Your Answer

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