0

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]

3
  • 2
    Well pop removes the last element.... so you are reading the values from the end.... Commented Feb 10, 2022 at 14:44
  • What is your question? What is weird about the result? What do you want to improve, specifically? Commented Feb 10, 2022 at 14:44
  • listToArray should output [10, 20, 30] but the result is [30, 20, 10] Commented Feb 10, 2022 at 14:48

2 Answers 2

1

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]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, make a stupid mistake
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.