Skip to content

Instantly share code, notes, and snippets.

@bfcoder
Created December 14, 2015 19:13
Show Gist options
  • Save bfcoder/f643dd19051669b9894c to your computer and use it in GitHub Desktop.
Save bfcoder/f643dd19051669b9894c to your computer and use it in GitHub Desktop.
Compare two arrays
// http://stackoverflow.com/a/17980268/1477165
// var arr1 = [1, 2, 3, 4];
// var arr2 = [2, 1, 4, 3]; // Loosely equal to 1
// var arr3 = [2, 2, 3, 4]; // Not equal to 1
// var arr4 = [1, 2, 3, 4]; // Strictly equal to 1
// arr1.equals(arr2); // false
// arr1.equals(arr2, false); // true
// arr1.equals(arr3); // false
// arr1.equals(arr3, false); // false
// arr1.equals(arr4); // true
// arr1.equals(arr4, false); // true
Array.prototype.equals = function (array, strict) {
if (!array)
return false;
if (arguments.length == 1)
strict = true;
if (this.length != array.length)
return false;
for (var i = 0; i < this.length; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].equals(array[i], strict))
return false;
}
else if (strict && this[i] != array[i]) {
return false;
}
else if (!strict) {
return this.sort().equals(array.sort(), true);
}
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment