Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Weird result of using recursion to concat array in javascript

I want to use recursion to build list to array function but the expected result is reversed to real solution. How could I improve the function of listToArray(list)

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return [list.value].concat(listToArray(list.rest));
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

pop() removes the last item so you are reading from the end to the start. So read from the start to the end using shift()

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.shift(), rest:null};
    }else{
        return {value:arr.shift(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return [list.value].concat(listToArray(list.rest));
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]

about 4 years ago · Juan Pablo Isaza Report

0

The simplest solution is to concat the other way around, so replace

[list.value].concat(listToArray(list.rest));

with

(listToArray(list.rest)).concat([list.value]);

See the snippet below

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return (listToArray(list.rest)).concat([list.value]);
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!