PDA

View Full Version : hard array question


BrightNail
01-23-2003, 01:14 AM
hey all,

lets see if the gurus can help out on this one.

is there a effective way to do the following:

1. test for the length of 2d arrays to find the one with the greatest length.

2. if the 'other' arrays are less than the greatest arrray in the 2d array, then append the 2d arrays with empty values so that all arrays are equal lenght..ala..

this:
var 2darray = new Array ( new Array ('10','20'), new Array('20','30','35'), new Array('10','15'));

would become:

var 2darray = new Array ( new Array ('10','20','n/a'), new Array('20','30','35'), new Array('10','15','n/a'));

now all subarrays contain 3 elements.

Please keep in mind that the largest subarray could exist anywhere in the Array 2darray...could be the first array, or the last....wherever..

I just need to find out the length of the largest subarray, and make sure the other arrays contain the same length if they are smaller...

any ideas?

james

A1ien51
01-23-2003, 02:57 AM
Sounds like hw to me, but I have the script already written, so look at this and see what it can do for you.

Basic idea....search through to find the lengths, after you find the largest, you add them on....not hard




LA = TheArray.length;
Big=0;
Fill="XX";

for(i=0;i<LA;i++){
LB = TheArray[i].length;
if(Big<LB)Big=LB;
}

for(i=0;i<LA;i++){
LB = TheArray[i].length;
for(j=LB;j<Big;j++){
TheArray[i][j]=Fill;
}
}

alert(TheArray[0]+"\n"+TheArray[1]+"\n"+TheArray[2]);

boywonder
01-23-2003, 03:09 AM
Yeah it;s pretty straightforward - I had it this way based on your question... (note variables can't start with a number)

<script language="JavaScript" type="text/javascript">
<!--
var twodarray = new Array(new Array('10','20'), new Array('20','30','35'), new Array('10','15'));
// grab length of biggest array
var i, j=twodarray.length, x=0;
for(i=0;i<j;i++) if(x<twodarray[i].length) x = twodarray[i].length;
// set the other arrays
for(i=0;i<j;i++) {
if(twodarray[i].length<x) while(twodarray[i].length<x) twodarray[i][twodarray[i].length] = 'n/a';
}
// show result of above
var str='';
for(i=0;i<j;i++) str+=twodarray[i]+'\n';
alert(str);
//-->
</script>

BrightNail
01-23-2003, 03:52 AM
hey all...

thanks...I did it slightly different..I ended working out a way...I'm not at work so I don't have the code verbatim..but what I did was.

use the Math.max method with all the subarrays in the method..

var test = Math.max (array[0].length,array[1].length etc..);

then I just looped thru the subarrays and if the subarray length was less than 'test' which held a reference to length of the longest array OF the subarrays...I appended a 'n/a' to the it till it equaled test....