trying to split arrays into teo seperate lists, en...
# cfml-general
g
trying to split arrays into teo seperate lists, ending up in an error https://trycf.com/gist/2b4ce6bee40d1ff2522d69b27fddd393/acf2023?theme=monokai Error: Cannot access array element at position 19. on line 10 what is wrong in this
s
Because
arraySlice()
wants the length of the slice, not the length of the original array.
a
It's almost as if the error message actually tells one that, too. 🤔
g
that above code did not worked for me so i tried this way and it works, used the mid to figure out its len and then use it
Copy code
<cffunction name="splitList" returntype="array">
        <cfargument name="list" type="string" required="yes">
        
        <cfset var arr = listToArray(arguments.list)>
        <cfset var len = arrayLen(arr)>
        <cfset var mid = int(len / 2)>
        
        <cfif len mod 2 eq 1>
            <cfset mid = mid + 1>
        </cfif>
        
        <cfset var firstHalf = arraySlice(arr, 1, mid)>
        <cfset var secondHalf = arraySlice(arr, mid + 1, len - mid)>
        
        <cfreturn [firstHalf, secondHalf]>
    </cffunction>
a
This is a good start, but I think you need to do some boundary checking. This errors if the list has zero or one elements. These were the first two tests I ran on it.
g
Great catch I did not considered it but I will add some more checks
👍 1
r
might not be a consideration, but also
arraySlice()
is not quite as performant when dealing with large arrays