Last Updated: February 25, 2016
·
1.465K
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside