Shuffle an XMLList

February 2, 2011 by fMajakovskij

If you have an XMLList object and want to shuffle its elements, simply use the following function.
This is pretty useful when you are loading an xml file and want to randomize its elements, i.e. a list of images.
Simply pass your XMLList loaded object to get a new, randomized, XMLList object:

public function shuffleXMLList(oitems:XMLList):XMLList
{
	var res:XMLList

	var indexarr:Array = []
	for(var i:int=0; i<oitems.length(); i++)
	{
		indexarr.push(i);
	}
	var len:int = indexarr.length;
	var arr2:Array = new Array(len);
	for(i = 0; i<len; i++)
	{
		arr2[i] = indexarr.splice(int(Math.random() * (len - i)), 1)[0];
	}

	var rndNodes:XML = new XML();

	for(i=0; i<arr2.length; i++)
	{
		var indx:int = arr2[i]
		var itm:XML = oitems[indx].copy();
		rndNodes.appendChild(itm);
	}
	res = rndNodes.children();
	oitems=null

	return res;
}

It will return a new XMLList object.

One thought on “Shuffle an XMLList

  1. Nathan says:

    could you give us an example of what you mean by “Simply pass your XMLList loaded object to get a new, randomized, XMLList object”

    how do I use this function? How do I pass the xml list into this function?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>