'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]
Solution 1:[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]
Solution 2:[2]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | epascarello |
| Solution 2 | Lajos Arpad |
