Comparing Arrays

Benchmark created by Tolga on


Test runner

Ready to run.

Testing in
TestOps/sec
Looping through each item
// attach the .compare method to Array's prototype to call it on any array
var array1 = ["1", "2", ["3", "4"]];
var array2 = ["1", "2", ["3", "4"]];

var compare = function(array1, array2) {
  // if the other array is a falsy value, return
  if (!array2)
    return false;

  // compare leng ths - can save a lot of time
  if (array1.length != array2.length)
    return false;

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

compare(array1, array2);
ready
JSON Encode
JSON.stringify(["1", "2", ["3", "4"]]) === JSON.stringify(["1", "2", ["3", "4"]]);
ready
ToString
return ["1", "2", ["3", "4"]].toString() === ["1", "2", ["3", "4"]].toString();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Tolga on