Entry
How do I create arrays based on an loop of variable number of records and then compare each array
Dec 4th, 2001 01:19
Jean-Bernard Valentaten, Shannon Ansbro,
Creating and filling an array is done like this:
var myArray = new Array();
var maxElement = 100; //or whichever size the array should have
for (i=0; i < maxElement; i++)
{
//now we assume that you have variables called myVar0 through myVar99
myArray[i] = eval('myVar' + i);
}
The eval-statement makes it possible to build variable-names
dynamically, as long as they are to be read!!! (left-side eval won't
work though).
Now for the comparison of arrays. The question is what comparison you
want to have. Should the arrays be equal, or should only their content
be equal. In the first case we do this:
function compareArray(oneArray, otherArray)
{
var ret = false;
if (oneArray.length == otherArray.length)
{
for (i=0; i< myArray.length)
ret = (oneArray[i] == otherArray[i])?true:false;
}
return ret;
}
Please keep in mind that both arrays are only counted as equal, when
(and only then):
a) they are of the same size
b) each pair of equal elements have the same index
If you just want to compare the content you will have to sort the arrays
first and then compare them.
In any case, if you want to efficiently work with arrays and lists, you
should consider getting a book about efficient algorithms.
HTH