Reputation: 53
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
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
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