-2

I have a quick question regarding using jQuery to compare 2 arrays. I have two arrays, and I need to call a function only if they are exactly identical (same size, elements, order).

For example, given these two arrays:

a['zero','one','two','three','four','five','six','seven', 'eight','nine'];
b['zero','one','two','three','four','five','six','seven', 'eight','nine'];

If these two are arrays are identical and in the same order, do:

do  function{};
Nightfirecat
  • 11,432
  • 6
  • 35
  • 51
rtn
  • 2,012
  • 4
  • 21
  • 39

4 Answers4

2

The isEqual method in underscore.js may be helpful if you don't want to handle the details yourself.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
  • hey thanks but I have to implement the solution using only current version of jQuery. I'll keep it in mind though. – rtn Nov 06 '12 at 22:34
0

A little type coercion avoids the loop:

var myarray=["Joe", "Bob", "Ken"];
    var myarray2=["Joe", "Bob", "Ken"];
    var myarray3=["Joe", "Beb", "Ken"];
if(myarray == ""+myarray2){alert("something");}
if(myarray == ""+myarray3){alert("something else");}​

http://jsfiddle.net/nY7Pk/

MaxPRafferty
  • 4,819
  • 4
  • 32
  • 39
0
var a=['zero','one','two','three','four','five','six','seven', 'eight','nine'];
var b=['zero','one','two','four','three','five','six','seven', 'eight','nine'];
var difference = [];

jQuery.grep(a, function(element, index) {
    if(a[index]!=b[index])
       difference.push(element);
});

if(difference.length>0){
   alert("Do something");
}

Tariqulazam
  • 4,535
  • 1
  • 34
  • 42
-1

Here is an example using plain JavaScript - which you can use alongside jQuery.

if (a.length === b.length) {
    var isMatch = true;
    for (var i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            isMatch = false;
            break;
        }
    }

    if (isMatch) {
        alert('It was all identical');
    }
}

If you want to allow juggling in your matches, you can change !== to !=.

!== will return false if the type or the value doesn't match.

!= will return false after juggling the types if the value doesn't match.

Fenton
  • 241,084
  • 71
  • 387
  • 401