Luke
Luke

Reputation: 20061

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]

Upvotes: 2

Views: 809

Answers (1)

John Whish
John Whish

Reputation: 3036

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)

Upvotes: 12

Related Questions