Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse an array

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

like image 228
Paul James Avatar asked Jan 19 '12 04:01

Paul James


4 Answers

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>
like image 166
Dale Fraser Avatar answered Oct 06 '22 18:10

Dale Fraser


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.

like image 37
Henry Avatar answered Oct 06 '22 18:10

Henry


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.

like image 45
Joseph Dykstra Avatar answered Oct 06 '22 17:10

Joseph Dykstra


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

like image 22
Mike Causer Avatar answered Oct 06 '22 18:10

Mike Causer