zjm1126
zjm1126

Reputation: 35662

How do I compare two arrays (which can have: DOM elements, numbers, strings, arrays or dictionaries) using jQuery?

I found this method:

Array.prototype.compare = function(arr) {
    if (this.length != arr.length) return false;
    for (var i = 0; i < arr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(arr[i])) return false;
        }
        if (this[i] !== arr[i]) return false;
    }
    return true;
}


var a = ['aa',[1,2,3]]
var b = ['aa',[1,2,3]]
alert(a.compare (b))

.
But, when I make a deep compare, it returns false.

So what method do you use to compare two arrays, using jquery?

Thanks

Upvotes: 2

Views: 820

Answers (1)

Yi Jiang
Yi Jiang

Reputation: 50095

There's no jQuery solution for this - jQuery is mainly used for DOM manipulation, ajax and some simple animations. It does come with a small collection of utilities, but as far as I know none of them have this function.

I did, however, find the bug in your code.

Array.prototype.compare = function(arr) {
    if (this.length != arr.length) return false;
    for (var i = 0; i < arr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(arr[i])) return false;
        } else { // <-- Here!
            if (this[i] !== arr[i]) return false;
        }
    }
    return true;
}

You need to use if - else here, instead of running both the .compare function again and comparing them with the equality operator.

Upvotes: 1

Related Questions