Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion equivalent to JavaScript array slice function?

I'm looking for some way to take the first x number of elements from an array (or list). Something that works similar to the Left() string function, or JavaScript's .slice() function.

So that it would do something like...

a = [1,2,1,3,4,5,1,6,7,8,1,9];
x = 10;
firstTen = ArrayLeft(a, x);
// ...or...
firstTen = ArraySlice(a, 1, x); 
//         ^ Returns the elements from 1 to 10: [1,2,1,3,4,5,1,6,7,8]
like image 438
Luke Avatar asked Mar 07 '26 14:03

Luke


1 Answers

In ColdFusion 9 you can just use the underlying Java methods to do it. Just need to remember that Java has 0 based arrays:

a = [1,2,1,3,4,5,1,6,7,8,1,9];
writedump(a.subList(0,10));

In ColdFusion 10+ you can use ArraySlice https://wikidocs.adobe.com/wiki/display/coldfusionen/ArraySlice

a = [1,2,1,3,4,5,1,6,7,8,1,9];
writedump(arraySlice(a, 1, 10));

This time the array is 1 based (as it normally is in CFML)

like image 156
John Whish Avatar answered Mar 10 '26 05:03

John Whish