function array_to_list(arr) {
list = null
for (i = arr.length; i >= 0; i--) {
list = { value: arr[i], rest: list };
}
return list;
}
x = array_to_list([10, 20]);
console.log(JSON.stringify(x));
the output I get is :
{"value":10,"rest":{"value":20,"rest":{"rest":null}}}
but I want
{value: 10, rest: {value: 20, rest: null}}
how can I solve that problem? That is to change the last rest to null instead of another object
2
Answers
To fix your code, set
i = arr.length - 1
as the initial value ofi
. Since arrays have 0 based index, the last item’s index is one less than the arrays length:I would use
Array.reduceRight()
to iterate the list from the end, and set the initial value tonull
:Array indexes are 0 based, so given the array
[10, 20]
the index of10
is0
and the index of20
is1
, but your loop starts fromarr.length
, which is 2, so the firstarr[i]
evaluates toundefined
and the loop runs one time more than it should. When iterating through an array backwards, you should generally start fromlength - 1
.