Hello,
I have a function arrayToList
that takes in an array and returns a list in the following format. Eg. for an array [1,2,3], the output is
{
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
I wrote the function with a recursion call as follows :
function arrayToList(arr) {
for(let i = 0 ; i < arr.length ; i++){
return {
value : arr[i],
rest : arrayToList(arr.slice(i + 1,arr.length))
}
}
}
However, the output is as follows
{ value: 1, rest: { value: 2, rest: { value: 3, rest: undefined } } }
How do I ensure I get a value of null
for the last rest
attribute in result body keeping the recursive nature of the code logic unchanged?