-3

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,114
  • 6
  • 33
  • 50
rtn
  • 1,961
  • 4
  • 19
  • 36

4 Answers4

1

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

Elias Zamaria
  • 89,268
  • 31
  • 107
  • 141
  • 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,611
  • 4
  • 29
  • 38
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,425
  • 1
  • 35
  • 40
-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
  • 224,347
  • 65
  • 373
  • 385