Select Page

Splitting An Array Into Groups In ColdFusion 2021

Published: March 27, 2022

The other day, I was dealing with a long list of IDs that I needed to use in a SQL query. In fact, the list was so long that the generated SQL statement was exceeding the max packet size property of the MySQL server. As such, I had to split the list of IDs into groups and perform the SQL query in chucks. I was surprised to see that our Utilities.cfc at work didn’t already have a user defined function (UDF) for this. As such, I wrote a function that splits an array into groups of a given max-length in ColdFusion.

The logic in this function is fairly simple: I’m using an old-school for-loop to iterate over the given collection is “group size” steps. Then, I’m just slicing-out the desired values. Really, the only complexity here at all is the fact that the Slice function in ColdFusion is NOT SAFE. As such, I have to take care when dealing with the end-bound of the array.

	values = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" ];
	writeDump( splitArrayIntoGroups( values, 5 ) );
	// ------------------------------------------------------------------------------- //
	// ------------------------------------------------------------------------------- //
	* I split the given collection into separate arrays, each of which has the given max
	* length.
	public array function splitArrayIntoGroups(
		required array collection,
		required numeric maxLength
		) {
		var collectionLength = collection.len();
		var groups = [];
		for ( var i = 1 ; i <= collectionLength ; i += maxLength ) {
			// CAUTION: The slice() method is NOT SAFE, and will throw an error if we go
			// out-of-bounds on the given collection. As such, we have to make sure that
			// our group-length argument never goes past the last index.
			var groupLength = min( maxLength, ( collectionLength - i + 1 ) );
			groups.append( collection.slice( i, groupLength ) );
		return( groups );

Here, we’re splitting the collection of 11 letters into groups of 5. And, when we run this ColdFusion code, we get the following output:

An array of 11-elements was split into 2 groups of 5-elements, and 1 group of the remaining 1-element.

As you can see, the collection of 11-letters was split into 3 groups: 2 of max-length 5 and then 1 that contained the remaining 1-element.

I really wish that the arraySlice() method in ColdFusion was safe. Having to worry about going out-of-bounds is quite a pain. A few years ago, I wrote an arraySliceSafe() function, and then demonstrated how many other Array-functions would become trivial to write.

Anyway, just a fun little weekend code kata. ColdFusion code is easy like a Sunday morning.