Last Updated: February 25, 2016
·
1.252K
· arn-e

Array comparison in plain JavaScript

Comparing two arrays in JavaScript :

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

1 Response
Add your response

With a few performance improvements :

Array.prototype.isEqualTo = function (compareTo) {
  var self = this // cache array
    , length = self.length // cache length
  if(length != compareTo.length) return false // compare numbers, strict equalty isn't necessary
  for(;length--;) if(self[length] !== compareTo[length]) return false // decrement is faster with for loops
  return true
}
over 1 year ago ·