Aliaspooryorik
ColdFusion ORM Book

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.


2 comments

  1. BTW: This of course is not going to work:

    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
  2. @Gert - great spot, I use that syntax for arrays all the time so should have spotted that :)

    Post updated!

    Comment by John Whish – December 13, 2011

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts