16 August 2010

How to split ActionScript Array in two or more

Until today my ActionScript Search Array functions have been downloaded 2386 times, according to Box.net counter. Despite of this number I do think every piece of code can and should be improved. That's way I'm adding new function:

splitTo(Array, int):Array

This function splits given Array to int parts. Resulting Array is two-dimensional. How it works?

Let's say you have Array of Numbers



Array a has 10 elements and you want to split this Array into 3 new Arrays. Resulting Array will return new Array as image shows.



As you can see remaining elements (in this case element 11) will be attached to last the Array. If you don't want to attach any residual elements just delete the only while loop in the code.

Here is the function:


// function splitTo splits array 'ar1' to 'parts' number of arrays

public static function splitTo(a1:Array, parts:uint):Array
{
if (parts > 1) {

var aCount:Number = a1.length / parts;
var limit:int = int(aCount);
var res:Array = new Array();

// if aCount <= 1
if (aCount <= 1)
{

// put every element in new array
for (var i:uint = 0; i<a1.length; i++)
{

// make new array and resulting array
var newarray:Array = new Array();
newarray.push(a1[i]);
res.push(newarray);
}
} else {
for (var k:uint = 0; k<parts; k++)
{
var newarray2:Array = new Array();

if (a1.length > 0)
{

// if a1 is not empty
for (var j:uint = 0; j<limit; j++)
{
newarray2.push(a1.splice(0, 1));
}
res.push(newarray2);
}
}

// put rest of the elements inside last array
while (a1.length > 0)
{
res[res.length-1].push(a1.splice(0, 1));
}
}

// return resulting Array of Array[s]
return res;
} else {
return a1;
}
}


More similar functions coming soon.
Stay updated by subscribing to blog RSS feed, or follow me on Twitter.
Thanks for sharing.

*_*

2 comments:

Gonza said...

Hi! I think this could be a code improvement:

Replace
if (parts > 1) {

With
if (parts > 1 && a1.length > 1) {

Then you can remove the "if aCount <= 1" part.

Shaun said...

This doesn't seem to work when trying to split an array of objects into groups. For my 32 objects, I try to split them into groups of 16 (per new array returned), but I end up with 8 arrays with two objects each. Any ideas?

 

template by blogger templates