Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linked List how to add value to from an array?

I am following a linked list problem in Eloquent JavaScript book and I don’t understand how the value for the first link is 10 and not 20 if i is = 1, in the first iteration of the for loop.

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = { value: array[i], rest: list }; //why is the value 10 and not 20 if i = 1, 
  }
  return list;
}
console.log(arrayToList([10, 20]));

{value: 10, rest: {value: 20, rest: null}}

I think I am thinking of the for loop the wrong way, but I don’t know where.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The value is 20. The explanation is that the loop is running backwards, adding list as a value of the property rest. Thus, the outermost object has the first value in the array and the innermost object has the last value in the array.

Have a look at this demo, where the console shows the values for each iteration:

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    console.log(`The index is ${i} and the value is ${array[i]}`)
    list = { value: array[i], rest: list }; //why is the value 10 and not 20 if i = 1, 
  }
  return list;
}
arrayToList([10, 20]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading