For an assignment in one of my classes we have to write many array functions. I am stuck on on function where we have to determine if two arrays are equal or not(as in have the same data in the same places, pretty much a clone of one another). The function has to be named function equals(array1, array2). Part of the code is provided all that needs to be done is the function part. Thanks for helping me out.
document.writeln("Equal Arrays<br />")
var a = initialize(3, 4, 5);
var b = initialize(3, 4, 5);
if (equals(a,b))
document.writeln("Arrays are equal<br />");
else
document.writeln("Array are different<br />");
I have to get back to class so I couldn’t really put together the greatest comparison function for arrays, but this is what I came up with in 2 minutes:
function equals(array1, array2){
var indicator = true;
for(var i = 0; i < array1.length; i++)
{
if(array1[i] != array2[i])
{
indicator = false;
return false;
}
else
indicator = true;
alert(indicator);
}
}
Or, if you have the Array.every() method, you can use this code:
array1.every(function(value, index) {
return value === array2[index];
});
The compatibility code for the every method, which provides all web browsers the ability to use it, is:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t && !fun.call(thisp, t[i], i, t))
return false;
}
return true;
};
}