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> 
2
  • See this SO answer: stackoverflow.com/questions/1773069/… Commented Nov 2, 2012 at 19:29
  • @rontornambe These arrays need to be in the same order too. one,two,three isn't the same as two,three,one for a quiz Commented Nov 2, 2012 at 19:31

2 Answers 2

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

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

9 Comments

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 This does check that. Is it not working for you?
No, it alerts me when there are the correct number of items, but says it is correct even when the order is incorrect.
Are you sure? It works for me - jsfiddle example
Show me an example where it fails and I'll see if I can help you
|
0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.