tags:

views:

96

answers:

5

Hi,

How to compare two array of strings using javascript ?

A: 

Take a look at the answer to this question.

David Neale
+1  A: 
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;
}

and here we go:

var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = [1,2,3,4,5,6,7,8,9,10];
alert(arr1.compare(arr2)); // true :D

EDIT: thanks to aioobe for the hint, i got this from here a while ago.

oezi
If the reference is the *Mastering Javascript Arrays* article you should provide the link.
aioobe
I thought about a prototype function, but what if one of your arrays is `null`?
xtofl
i had this in my scripts for an old project and forgot where it comes from - but after is visited your link, i think it was Mastering Javascript Arrays.
oezi
+1  A: 

There are no function created for comparing string arrays as writing your own as easy enough:

function compareStringArrays(a,b) {
    if (a == null && b == null)
        return true;

    if (a == null || b == null)
        return false;

    if (a.length != b.length)
        return false;

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

    return true;
}
Max
hm... we apparently thought the same :)
xtofl
why Math.min? you only get there if both lenths are the same... simply write a.length to save time.
oezi
Yeah, I've just noticed it myself and edited. First version was without length-checks, and I forgot to remove Min after I added length-checking.
Max
A: 

There is already a similar question in SO at http://stackoverflow.com/questions/1773069/using-jquery-to-compare-two-arrays, check it out

mohang
A: 

If you want to determine if 2 arrays of strings are identical- each contains only the same elements, in the same order- you can use a simpler construction.

var a=['a','b','c','d','e','f','g'],
b=['a','b','c','d','e','f','g'],
c=['a','b','c',,'d','e','f','g'],
d=['a','b','c',,'d','e','g','f']

a.join(',')==b.join(',')  // true

a.join(',')==c.join(',') // false, c contains an undefined element
c.join(',')==d.join(',') // false, order is diffferent
kennebec