Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

72
Views
Convert a list to array in JavaScript - how to make sense of this for loop

I am given a list -

let listA = {value: 10, rest: {value: 20, rest: { value: 30, rest: null }}}

I need to convert it into an array -

[10, 20, 30] 

I used this for loop to go over the keys in list

It did not work. Eloquent JS book uses this for loop -

 let array = [];
  for (let node = list; node; node = node.rest){
    array.push(node.value);

I am a beginner. I have only encountered simple for loops such as -

for(let i=0; i <= array.length; i++) 

and similar versions.

What is happening with this for loop syntax ?

This for loop works but don't know how

7 months ago · Santiago Trujillo
2 answers
Answer question

0

Your "list" is a linked list. It is modeled as recursively nested objects. You need either a recursive algorithm or keep track of your current "stack" manually when writing in iterative form.

let array = [];
for (let node = list; node; node = node.rest) {
  array.push(node.value);
}

Takes the first object, pushes it into the array, then lets the current object point to node.rest (the inner, nested object) and repeats this until the current object no longer points anywhere (node is shorthand for !!node: it tests the value to be truthy. Not quite right, but you can think of it as node != null).

If you are not accustomed to non-indexed for-loops, it can easily be translated into a while loop with the same behavior:

let array = [];
let node = list;
while (node) { // shorthand for `!!node`: tests the value to be truthy
  array.push(node.value);
  node = node.rest;
}

The variable node assumes the following values in order:

  1. { value: 10, rest: { value: 20, rest: { value: 30, rest: null } } }
  2. { value: 20, rest: { value: 30, rest: null } }
  3. { value: 30, rest: null }
  4. null
7 months ago · Santiago Trujillo Report

0

Your input object is nested json object with value key and rest as next object.

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

For loop that you have put is iterating over the nested object

  1. In first iteration it takes the root object pushing value 10 to the array.

  2. In 2nd iteration it takes the first nested object reading value 20 and it pushes it to the array.

  3. In 3rd iteration it reads next nested object and pushes value 30 to the array.



7 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.