Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my recursive function not returning the last element in the array?

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:

Task from:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);}
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading