Time for another gotcha. Imagine you are a new ColdFusion developer and you need to sort an array. If you are like me, you may not read the complete documentation for the function. (I know I'm not the only one who skims the docs.) You see that there is an arraySort function so you write code like so:
<cfset myarray = arraySort(myarray, "numeric")>
You then go to display the array by looping over it and get an error. Why? It turns out the arraySort function (and others that I'll list below) actually returns true or false and operates on the array you pass in. The docs say that arraySort will return false if the sort failed. I haven't found a case where that actually happens. If you try to sort an array of strings numerically, for example, it throws an error.
That aside - it is definitely something that can trip a user up. Most folks will use a temporary variable to handle the sort:
<cfset result = arraySort(myarray, "numeric")>
But you don't need to do that. You can write it a bit shorter:
<cfset arraySort(myarray, "numeric")>
This begs the question - what if you want to sort an array and keep the original as is? Use a copy created by duplicate:
<cfset newArr = duplicate(arr)>
<cfset arraySort(newArr, "numeric")>
So which array functions act like this? (Note - I'm only listing the ones that may trick you up. For example, arrayIsEmpty returns a boolean but I'm sure folks expect that.)
arrayAppend
arrayClear
arrayDeleteAt
arrayInsertAt
arrayPrepend
arrayResize
arraySet
arraySort
arraySwap
Archived Comments
What's the difference between using duplicate() and just doing
<cfset newArr = arr>?
On the matter of CF Arrays. How do you sort more dimensional arrays. I know have a very complicated function to do this, but I can imagine there are some standard features to do this.
sometimes I've used:
cfif not arraySort(myarray, "numeric")
to set and test. if it trips the if I kick it out or try to remediate the problem. It acts flaky sometimes though I've found.
@Raymond - if the array isn't simple, this creates a pointer. Safest to just duplicate.
@Martijn - I'd either use a custom sort, or use structs which has a more complex structSort func.
@DK - thats my question - WHEN does it return false?
I can say confidently in two years I've never seen one entry for the 2 areas I've used this in at about 100 users online during business hours.
Sorry don't know the answer =\
I have to admit that the boolean return value thing has completely *kicked my ass* a few times. I learned my lesson so well that now I regularly find myself doing stuff like this:
<cfset listAppend ( myList, myvalue ) />
Argh.
Great tip Ray! I always wrote <cfset temp = ArraySort(yadda, "yadda") /> Now I can shave off 0.77 seconds of coding with <cfset ArraySort(yadda, "yadda") />
Woo hoo!