Reverse an array in ColdFusion and other tricks using slice syntax adding ColdFusion 2018
In ColdFusion there is a dedicated function to reverse a string but there isn’t one to reverse an array. With the slice functionality added in ColdFusion 2018 you can easily reverse an array:
foo = [10,20,30,40,50]; bar = foo[::-1]; writeDump(foo); // outputs [10,20,30,40,50] writeDump(bar); // outputs [50,40,30,20,10]
As you can see foo
is unchanged and we have a new array bar
which is in the reverse order to foo
.
With this syntax we can also do things like picking the value of every element with an odd index starting at position 1.
foo = [10,20,30,40,50,60,70,80,90,100]; oddElements = foo[1::2]; writeDump(oddElements); // outputs [10,30,50,70,90]
As the start position defaults to 1
we could have written the above example as:
foo = [10,20,30,40,50,60,70,80,90,100]; oddElements = foo[::2]; writeDump(oddElements); // outputs [10,30,50,70,90]
If you want to pick the value of every element with an even index starting at position 2.
foo = [10,20,30,40,50,60,70,80,90,100]; evenElements = foo[2::2]; writeDump(evenElements); // outputs [20,40,60,80,100]
This one will return every 3rd element starting at position 2.
foo = [10,20,30,40,50,60,70,80,90,100]; thirdElementsStartingFromPositionTwo = foo[2::3]; writeDump(thirdElementsStartingFromPositionTwo); // outputs [20,50,80]
This one will return every 3rd element starting at position 2 up to and including position 5.
foo = [10,20,30,40,50,60,70,80,90,100]; bar = foo[2:5:3]; writeDump(bar); // outputs [20,50]
You can also use it to clone an array:
foo = [10,20,30,40,50]; bar = foo[:]; bar.deleteAt(1); writeDump(foo); // outputs [10,20,30,40,50] writeDump(bar); // outputs [20,30,40,50]
Get the first 3 elements of an array
foo = [10,20,30,40,50]; writeDump(foo[:3]); // outputs [10,20,30]
Get all elements from position 5 (including the value at position 5)
foo = [10,20,30,40,50,60,70,80,90,100]; writeDump(foo[5:]); // outputs [50,60,70,80,90,100]
Get all elements from position 5 (including the value at position 5) excluding the last 4 elements.
foo = [10,20,30,40,50,60,70,80,90,100]; writeDump(foo[5:-5]); // outputs [50,60]
The fun doesn’t have to stop with number arrays, we can do the same with sentences. For example we can split the sentence up into an array of words using a space as the delimiter, reverse it, and then join it back together again.
message = "am I as old as you are"; words = message.split(" "); reversed = words[::-1].toList(" "); writeDump(reversed); // are you as old as I am
I think this is great addition to CFML. There are some more examples in the docs:
https://helpx.adobe.com/coldfusion/developing-applications/the-cfml-programming-language/using-arrays-and-structures/populating-arrays-with-data.html#slicing