Quicksort Result is a String (Resolved)

I’m having with my quickSort function returning a string instead of an array. Any advice on how to properly return the values created by the recursion function?

let log = console.log

function quickSort(arr) {
    
    let localArray = arr.slice()
    
    function recursion (array) {
        if (array.length<2) {return array}
        let lowArray = []
        let highArray = []
        let pivot = array[0]
        
        for (let i=1;i<array.length;i++) {
        if (array[i] < pivot) {lowArray.push(array[i])}    
        
        else if (array[i] > pivot) {highArray.push(array[i])}
        }
        return recursion(lowArray) + pivot + recursion(highArray)
        
    }
    
    return recursion(localArray)
    
}

let r = quickSort([4,2,3,6,5,8,7,9,0,1])
log(r)
log(typeof r)

maybe run parseInt() on your return value to change it from a string to a number?

what error are you getting exactly?
or rather what problems are you having?

return recursion(lowArray) + pivot + recursion(highArray)

the + operator is what is changing your array to a string, this is a case of type coercion that is giving unexpected results.
Type coercion explained:






you need a method that chain array together, for example concat()

2 Likes

Thanks for the feedback, the concat method did the trick. Changing this line

return recursion(lowArray) + pivot + recursion(highArray)

to this

 return Array.prototype.concat(recursion(lowArray), pivot, recursion(highArray))

made the quickSort work as intended. Thanks!

But you have not read the documentation, because that’s not how it is described there

Well, unfortunately reading the documentation and understanding the documentation aren’t synonymous lol. I’ll read it again.

You call concat on an array
arr1.concat(arr2,arr3)