Home > front end >  Array to list in Javascript
Array to list in Javascript

Time:09-26

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = {value: array[i], rest: list};
  }
  return list;
}

// output
console.log(arrayToList([10, 20, 30, 40, 50]));
// → {value: 10, rest: {value: 20, rest: null}}

since array.value = array[i] and in the loop the condition is set to start from array.length -1 which is the last index of the array, so I was thinking why the output is not inverted? my understanding is list should start at 50 and decrements from there until reached 10.
Can anyone help why the condition of the loop is set this way and not (i = 0; i < array.length -1; i ). Thank you.

CodePudding user response:

The first time around the loop it creates an object:

{
  "value": 50,
  "rest": null
}

The second time around the loop, it puts that inside the new object it creates.

And so on.

Hence, "value": 50 is the innermost value.

CodePudding user response:

What your code snippet does is for each value in your array, it will take it and change list to be

list = {value: *, rest: null}

It then repeats the process again, but then comes to the same instruction. In your code, the value rest is set to be list inside of itself. So it then takes the next value and changes rest inside of list to be

{value: *, rest: null}

So list's value turns into:

list = {value: *, rest: {value: *, rest: null}

The fix is using a separate array:

const ArrayToList = (Array) => {
    List = {Value: null, Rest: RestArray};
    RestArray = [];
    
    // Set the first value:
    List.Value = Array[0]
    
    // Loop through the rest:
    for (let i = 1; i < (Array.length - 1); i  ) {
        RestArray[i] = Array[i]
    }

    return List
}

CodePudding user response:

you can do this by following the "natural" order of your array, it's just a matter of conciseness

function arrayToList(arr) 
  {
  let list = null, listTop = null;

  for (let value of arr) 
    {
    if (list===null)  
      {
      list    = { value, rest:null }
      listTop = list
      }
    else
      {
      list.rest = { value, rest:null }
      list = list.rest
      }
    }
  return listTop;
  }

// output
console.log( arrayToList([10, 20, 30, 40, 50]) ) 

  • Related