Search code examples
javascriptarrayslistobject

Convert array to list in javascript


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


Solution

  • To fix your code, set i = arr.length - 1 as the initial value of i. Since arrays have 0 based index, the last item's index is one less than the arrays length:

    function array_to_list(arr) {
      let rest = null
    
      for (let i = arr.length - 1; i >= 0; i--) {
        rest = { value: arr[i], rest };
      }
    
      return rest;
    }
    
    const result = array_to_list([10, 20]);
    console.log(JSON.stringify(result));

    I would use Array.reduceRight() to iterate the list from the end, and set the initial value to null:

    const array_to_list = arr =>
      arr.reduceRight((rest, value) => ({
        value,
        rest
      }), null)
    
    const result = array_to_list([10, 20]);
    console.log(JSON.stringify(result));