0

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.

1
  • That list implementation doesn't really make any sense. Typically nodes have a pointer (or reference in this case) to the next element, and how you have this it will have circular references. Commented Sep 25, 2022 at 23:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

Thank you this clear but just one question. I thought something[i] could only be done if that something[i] is in the for loop condition. How could you do RestArray[i]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.