Austin Ballard
Austin Ballard

Reputation: 143

Why is this sorting function returning undefined?

The result that's logged to the console (answer) is the correct one, but it's coming out of the function as undefined. What is going on?

let sorted = [];

function reset(){
    sorted = [];
}

function sort(list) {
    let least = list[0];
    for (let i = 0; i < list.length; i++){
        if (list[i] < least ){
            least = list[i];
        }
    }
    sorted.push(least);
    list.splice(list.indexOf(least),1);
    if (list[0] !== undefined){
        sort(list)
    }
    else {
        let answer = sorted;
        reset();
        console.log(answer);
        return answer;
    }
}
let sampleArray = [3,2,1];
sort(sampleArray);

Upvotes: 1

Views: 613

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51936

@Mureinik is correct about the problem. However, more to the point, if you want to make a sorted copy of the array in increasing order, you can easily do so using .slice() and .sort():

let sampleArray = [3, 1, 2];
// sorted array
let sortedArray = sampleArray.slice().sort((a, b) => a - b);

console.log(sortedArray);
// original array preserved
console.log(sampleArray);

(I'm getting a 500 error so here's an alternative demo for now)

Upvotes: 0

Mureinik
Mureinik

Reputation: 311893

In the if branch you correctly call sort recursively, but just ignore the returned value instead of returning it. Just return it and you should be fine:

if (list[0] !== undefined) {
    return sort(list); // Here
}
else {
    // Rest of your code...

Upvotes: 1

Related Questions