How to change an array

Hi I have an array of strings, and I need to output them from the last to the first.

I don't see the arrayReverse() function, but I'm just learning ColdFusion

+6
source share
5 answers

You can just iterate 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 actually modify the array.

 <cfscript> // and for those who use cfscript: for ( var i = arrayLen( myArray ); i >= 1; i-- ) { writeOutput( myArray[i] ); } </cfscript> 
+12
source

Oh, but there is an ArraySort method!

ArraySort( array, sort_type [, sort_order] );

Returns a boolean value.

array 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-ab/arraysort.html

+1
source

I wrote this function to access 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 tested it and it works with 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 in my own component, so it is easier to use in different projects.

+1
source

The 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 write arrayReverse() , because the array is passed by value in CF (not until CF2016 this.passArraybyReference ), so it is inefficient.

+1
source
 <cfscript> test = [ "a", "b", "c", "d" ]; writeDump(listToArray(reverse(arrayToList(test)))); </cfscript> 

Will do the trick.

0
source

Source: https://habr.com/ru/post/906366/


All Articles