PDA

View Full Version : Problem Extracting Array Items to Another Array


thepeskykid
04-29-2003, 06:17 PM
Hello,

I have been struggling with this for a couple of hours now and I can't see the wood for the trees...

function process_debts()
{
if (mainArray.length == 0)
{
alert("You must have entered at least one debt");
return;
}
var tempArray1 = new Array(2);
var tempArray2 = new Array(0);
for (i=0; i<mainArray.length; i++)
{
tempArray1[0] = mainArray[i][0];
tempArray1[1] = mainArray[i][4];
tempArray2[i] = tempArray1;
}
}

the above is supposed to iterate through the 2 dimensional array mainArray (which contains numerous arrays, each containing 7 items), copying items 0 and 4, placing these copies into 'slots' 0 and 1 of the temporary array tempArray1, then adding this 2 item array to the end of another array (tempArray2)

E.G.

if mainArray = ( (1,2,3,4,5,6,7) , (2,3,4,5,6,7,8) )

#1 iteration, tempArray1 = (1,4)
#2 iteration, tempArray1 = (2,5)

resulting in...

tempArray2 = ( (1,4) , (2,5) )

but I get...

tempArray2 = ( (2,5) , (2,5) )

Can anyone point out what I am doing wrong?

Thank you

Jason
04-29-2003, 10:54 PM
you can try changin tempArray2[i] =tempArray1 to something like tempArray = tempArray2 + tempArray1 so that it concatinates tempArray1 on to tempArray2 which will be empty on its first iteration through the loop...see if that works...


Jason

cheesebagpipe
04-30-2003, 07:05 AM
When you do this:

tempArray2[i] = tempArray1;

....it might look like you're copying the (primitive) values from the RH array over to the LH one. But JS arrays are objects; when you do the above, you're actually copying a reference - pointer, of sorts - to the RH object into the LH one. Referencing tempArray2[i] will now simply zip you over to the tempArray1 object. In essence:

var x = Object;
x.property = 'old'; //set property property
var ref = x; //set object reference
alert(ref.property); //now refers to x object
x.property = 'new'; //change original
alert(ref.property); //same

If you want to copy values from one array to another, you need to do it explicitly, value for value - if you just set one object 'equal' to another, you'll end up looking at the same object.

var mainArray = [ [1,2,3,4,5,6,7] , [2,3,4,5,6,7,8] ];

function process_debts()
{
if (mainArray.length == 0)
{
alert("You must have entered at least one debt");
return;
}
var tempArray1 = new Array(2);
var tempArray2 = new Array(0);
for (i=0; i<mainArray.length; i++)
{
tempArray1[0] = mainArray[i][0];
tempArray1[1] = mainArray[i][4];
tempArray2[i] = [tempArray1[0] , tempArray1[1]];
alert(tempArray2);
}
}

process_debts();

Don't forget, JS counts from zero. This (http://forerunners.org/WebLibrary/jscript/ch09_03.htm) should help.

thepeskykid
04-30-2003, 08:14 AM
Ah... I understand where I was going wrong now

Thank you

:D