Recursively compare an array to another array - Node.js Array

Node.js examples for Array:Compare Array

Description

Recursively compare an array to another array

Demo Code


(function() {/*from w w w.jav a2s. c o  m*/
"use strict";

/**
 * Recursively compare an array to another array.
 *
 * @param array array Array to compare with
 * @return boolean
 * @author http://stackoverflow.com/a/14853974/2113023
 */
Array.prototype.compare = function (array) {
  // if the other array is a falsy value, return
  if (!array)
    return false;

  // compare lengths - can save a lot of time
  if (this.length != array.length)
    return false;

  for (var i = 0; i < this.length; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
      // recurse into the nested arrays
      if (!this[i].compare(array[i]))
        return false;
    }
    else if (this[i] != array[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false;
    }
  }
  return true;
}

})();

Related Tutorials