user1791449
user1791449

Reputation: 53

jQuery need a simple way to compare arrays then display an alert for equal and other for false

Is there a simple way of comparing two arrays, then having an alert (or some other function later on) pop up if the arrays are equal, and one when it is not?

Here is my array

var answerKey = ["four", "two", "one", "three"];
var answers = [];

jQuery I have so far for this

$("#subBtn").click(function() {
$('#bin a').each(function() {
    answers.push($(this).attr('name'));
})
console.log(answers);
});

HTML

<ul>
    <li><a draggable="true" href="#" id="one" name="uno" class="imgHvr">One</a></li>
    <li><a draggable="true" href="#" id="two" name="dos" class="imgHvr">2</a></li>
    <li><a draggable="true" href="#" id="three" name="tres" class="imgHvr">three</a></li>
    <li><a draggable="true" href="#" id="four" name="sweet" class="imgHvr">4</a></li>
</ul>

Upvotes: 0

Views: 423

Answers (2)

Mike Park
Mike Park

Reputation: 10941

Just compare both arrays element by element.

function arraysEqual(arr1, arr2){
    if (arr1.length != arr2.length) return false;

    for (var i=0;i<arr1.length;i++){
        if (arr1[i] != arr2[i]) return false;
    }

    return true;
}

Click handler...

 $("#subBtn").click(function() {
    var answers = [];
    $('#bin a').each(function() {
        answers.push($(this).attr('name'));
    }); 

    console.log(answers);

    if (!arraysEqual(answerKey, answers)) {
        alert("something");
    }
});

Copy this exactly

Upvotes: 1

Nahuelistico
Nahuelistico

Reputation: 42

If you don't want to compare element by element, this should work:

if (JSON.stringify(array_1) == JSON.stringify(array_2)){
....
}

Upvotes: 0

Related Questions