Hi,
How to compare two array of strings using javascript ?
Hi,
How to compare two array of strings using javascript ?
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.
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;
}
There is already a similar question in SO at http://stackoverflow.com/questions/1773069/using-jquery-to-compare-two-arrays, check it out
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