1

I need a very simple 'knowledge check' which should compare the selected answers with the correct answers. I placed the correct answers into an array, and the selected answers into another array:

$(".kc_submit_1").click(function () {

        var correctAnswers = ['true','true','true','true','true'];
        var allAnswers = [];

        $('.kc_answer').each(function() {
                allAnswers.push($(this).val());
        });

        if (allAnswers==correctAnswers) {
            alert ('Yahtzee');
        };

})

The problem is that I never get a Yahtzee. The IF function is never true, which it should be if you clicked all items.

Fiddle: http://jsfiddle.net/dN6vt/

Jen
  • 1,663
  • 1
  • 17
  • 34

2 Answers2

4

Try

$(".kc_submit_1").click(function () {
    var correctAnswers = ['true', 'true', 'true', 'true', 'true'];
    var allAnswers = $('.kc_answer').map(function (i) {
        return correctAnswers[i] == this.value ? this.value : undefined;
    });
    //alert (correctAnswers);
    //alert (allAnswers);
    if (allAnswers.length == correctAnswers.length) {
        alert('Yahtzee');
    };

})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

You'll need to do this via a loop, since arrays are objects in JavaScript, and different objects have different object ids, which means javascript will never recognise them as equal. To make this particular script work, you could do the following:

$(".kc_submit_1").click(function () {

    var correctAnswers = ['true','true','true','true','true'];
    var allAnswers = [];
    var wrongAnswers = [];

    $('.kc_answer').each(function() {
        currInd = allAnswers.length;
        allAnswers.push($(this).val());
        if (allAnswers[currInd] != correctAnswers[currInd])
            wrongAnswers[currInd] = $(this).val();
    });

    if (wrongAnswers.length) {
        alert ('Yahtzee');
    };

})

In any other situation, you could just use a function like this one:

function compareArray(arr1, arr2) {
    var clone2 = arr2.slice(0);
    var difflen = 0;
    for (var i=0;i<arr2.length;i++) {
        if (i in arr1 && arr1[i] == arr2[i]) {
            clone2[i] = undefined;
        } else {
            difflen++;
        }
    }
    clone2.len = difflen;
    return clone2;
}

This function will return an array with all the values in array 2 that were not equal to the values in array 1. To get the amount of differences there are, you need to do compareArray(arr1, arr2).len.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95