Hi I have an array of strings, and I need to output them from the last one to the first one.
I don't see an arrayReverse()
function, but I'm only just learning ColdFusion
You can just loop over the array in reverse
<cfloop index="i" from="#arrayLen(myArray)#" to="1" step="-1">
<cfoutput>#myArray[i]#</cfoutput>
</cfloop>
I think you need to use Java methods to really reverse the array.
<cfscript>
// and for those who use cfscript:
for ( var i = arrayLen( myArray ); i >= 1; i-- ) {
writeOutput( myArray[i] );
}
</cfscript>
FYI array in CF is just an ArrayList, so...
arr = [1,2,3];
createObject("java", "java.util.Collections").reverse(arr);
writeDump(arr); // arr becomes [3,2,1]
And I would not bother writing arrayReverse()
because array is passed by value in CF (not until CF2016's this.passArraybyReference
) so it's super inefficient.
I wrote this function to reverse an array. It modifies the array and returns it.
function init(required array arr) {
var arrLen = arrayLen(arr);
for (var i = 1; i <= (arrLen / 2); i++) {
var swap = arr[arrLen + 1 - i];
arr[arrLen + 1 - i] = arr[i];
arr[i] = swap;
}
return arr;
}
I've tested it, and it works on arrays of strings, as well as objects, etc.
writeOutput(arrayReverse(['a','b','c']) ); // => ['c', 'b', 'a']
var a = ['apple', 'ball', 'cat', 'dog'];
arrayReverse(a);
writeOutput(a); // => ['dog', 'cat', 'ball', 'apple']
I put it into it's own component, so it's easier to use in different projects.
Oh but there is an ArraySort method!
ArraySort( array, sort_type [, sort_order] );
Returns boolean.
array
is updated by reference.
sort_type
can be numeric
, text
or textnocase
sort_order
can be asc
or desc
<cfscript>
test = [ "c", "d", "a", "b" ];
arraySort( test, 'textnocase' );
test is now:
[ "a", "b", "c", "d" ]
</cfscript>
Check out the documentation here:
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-a-b/arraysort.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With