skip to Main Content
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


  1. 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));
    Login or Signup to reply.
  2. Array indexes are 0 based, so given the array [10, 20] the index of 10 is 0 and the index of 20 is 1, but your loop starts from arr.length, which is 2, so the first arr[i] evaluates to undefined and the loop runs one time more than it should. When iterating through an array backwards, you should generally start from length - 1.

    function array_to_list(arr) {
      list = null
    
      for (i = arr.length - 1; i >= 0; i--) {
        list = { value: arr[i], rest: list };
      }
    
      return list;
    }
    x = array_to_list([10, 20]);
    console.log(JSON.stringify(x));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search