Using Slice() in ColdFusion
I just asked on Twitter, if there was a ColdFusion equivalent of JavaScript's .slice() method and Railo's arraySlice function. I wanted to use slice as having to iterate over the array deleting items is very inefficient.
Marc Esher replied pointed me at Java's subList method.
My first attempt at using it in ColdFusion was to do this:
<cfscript>
arrayA = [1,2,3,4,5,6,7];
WriteDump( arrayA.subList(2,4) );
</cfscript>
Next I tried converting a list to an array like so:
<cfscript>
arrayB = ListToArray( "1,2,3,4,5,6,7" );
WriteDump( arrayB.subList(2,4) );
</cfscript>
This also worked.
Out of curiousity I then tried:
<cfscript>
arrayC = ListToArray( ArrayToList( ["1,2,3,4,5,6,7"] ) );
WriteDump( arrayC.subList(2,4) );
</cfscript>
This also worked.
Finally I tried this which also worked:
<cfscript> arrayD = ArrayNew( 1 ); arrayAppend( arrayD, 1 ); arrayAppend( arrayD, 2 ); arrayAppend( arrayD, 3 ); arrayAppend( arrayD, 4 ); arrayAppend( arrayD, 5 ); arrayAppend( arrayD, 6 ); arrayAppend( arrayD, 7 ); WriteDump( arrayD.subList(2,4) );
</cfscript>
One final thing to note is that in Java, Arrays are zero based.
- Posted in:
- ColdFusion
- Railo


arrayA = ["1,2,3,4,5,6,7"];
WriteDump( arrayA.subList(2,4) );
since you are creating an array with one element. it should be:
arrayA = [1,2,3,4,5,6,7];
WriteDump( arrayA.subList(2,4) );
Gert
Comment by Gert Franz – December 13, 2011
Post updated!
Comment by John Whish – December 13, 2011