1

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);
1
  • 5
    In your if branch you have no return, which means you get the default return value (undefined). Commented Apr 17, 2018 at 15:42

2 Answers 2

1

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...
Sign up to request clarification or add additional context in comments.

Comments

0

@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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.