so i was going through the course of FreeCodecamp and stumbled upon this task which I solved with a for-loop. But to test my knowledge about recursive function I wanted to give it a try. But for some reason the array at the end only contains the third and second element.
Code:
const result = {
success: ["max-length", "no-amd", "prefer-arrow-functions"],
failure: ["no-var", "var-on-top", "linebreak"],
skipped: ["no-extra-semi", "no-dup-keys"]
};
const failureItems = [];
function makeList(arr) {
// Only change code below this line
// for (let i = 0; i < arr.length; i++)
// {
// failureItems.push(`<li class="text-warning">${arr[i]}</li>`);
// }
if(arr.length === 1){
return arr[0];
} else {
failureItems.push(`<li class="text-warning">${arr.pop()}</li>`);
if(arr.length >= 1){
makeList(arr);}
}
console.log("Log before return:" + failureItems[0]);
// Only change code above this line
return failureItems;
}
const failuresList = makeList(result.failure);
console.log(`Failure list is ${failuresList}`);
I added console.log where I thought the problem occurs but I just cant pinpoint the line that gives me trouble.
>Solution :
you are not pushing first element ever.
although recursion might not be the best solution the way you are doing it.. but you can recurse till array is empty
if(arr.length === 0){
return;
} else {
failureItems.push(`<li class="text-warning">${arr.pop()}</li>`);
if(arr.length >= 1){
makeList(arr);}
}