0

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>
user1791449
  • 53
  • 1
  • 1
  • 7

2 Answers2

1

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

Mike Park
  • 10,845
  • 2
  • 34
  • 50
  • When this code runs, it checks is checking to make sure there are the correct number of items and it works just fine. I am also needing it to check to make sure that the order of both arrays match also. What is the best and easiest way to add that? – user1791449 Nov 07 '12 at 18:11
  • @user1791449 This does check that. Is it not working for you? – Mike Park Nov 07 '12 at 18:20
  • No, it alerts me when there are the correct number of items, but says it is correct even when the order is incorrect. – user1791449 Nov 07 '12 at 18:22
  • Are you sure? It works for me - [jsfiddle example](http://jsfiddle.net/VY5JF/2/) – Mike Park Nov 07 '12 at 18:31
  • Show me an example where it fails and I'll see if I can help you – Mike Park Nov 07 '12 at 18:33
  • I am obviously still a newbie with jQuery, and javascript so any help would be great! Here is what I am working with right now. [My code](http://jsfiddle.net/tjaymz/QVynj/). – user1791449 Nov 07 '12 at 18:35
  • I see what you did. You changed my code to something that doesn't work. See my edit – Mike Park Nov 07 '12 at 18:47
  • PERFECT!! Thank you so much! I will try to be more careful when I copy then mess up someones example like that. – user1791449 Nov 07 '12 at 18:54
  • @user1791449 No worries, it happens. You can mark my answer as correct using the checkmark – Mike Park Nov 07 '12 at 18:55
0

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

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