Creating a List Object from Array in Javascript

Kiong

I am going through Javascript from the beginning. No shortcuts, no framework, nothing. Just plain Javascript. And just for the fun of it, I am doing every exercise. Now, when I get to this one question:

Write a function arrayToList that builds up a data structure like

var list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};

My code has to be able to fulfill the following:

console.log(arrayToList([10, 20])); 
// → {value: 10, rest: {value: 20, rest: null}} <== expected output which I am sure you know

I tried to do this recursively as the later question wants us to do it recursively (recursion is one of my weakest points!). But, I got the following code up:

var list = 
    {
      value: 0,
      rest: null
    }

function arrayToList(array)
{   
  list.value = array.shift();

    if(array.length!=0)
    {
      list.rest = arrayToList(array);
    }
  else
  {
    list.rest = null;
    console.log(list); //this outputs to {value: 20, rest: null}
    return list;
  } 
  return list;
};

However, the output

{value: 20, rest: {value: 20, rest: {
                                      value:    20
                                      rest: {value: 20, rest: {value: 20, …}}
}}} 

The ... refers to the same block of

{value:20, rest:{value:20, rest: {...}}

Well, I did not expand to the end to see (its too long! (after about 20 times opening is still the same) IF there is an end at all).

Hoping to have someone guide me to the answer. I have spent couple of days on this already and am stuck.

Thanks a lot and have a good day all!

Shai

Guidance (hopefully!)

You do not need a global list variable, like you're currently using (unless you're trying to do some complex optimisation – don't worry about it for now). In fact, it looks like this global list variable is what's causing your problems. I will try to walk you through the correct way to do this from the beginning.

First, try to identify what the 'repeated' part of the output needs to looks like. In your case, the repeated part is:

{
    value: someValue,
    rest: RECURSION
}

because if you swap RECURSION for that SAME structure above, you get the exact cascading effect you need:

{
    value: someValue,
    rest: {
        value: someValue,
        rest: RECURSION
    }
}

and so on.

Once you've identified that, your function literally just needs to return that object. It is that simple. Swap someValue for that front value (i.e. the return value of arr.shift()), and swap RECURSION for a call back to your function, passing it the rest of the array. Which gives:

function arrayToList(arr) {
    var value = arr.shift();

    return {
        value: value,
        rest: arrayToList(arr) // arr has already had its front value removed, by .shift()
    };
}

The only thing left to add is an end condition, so that if there are no more values left the recursion just returns null (otherwise we'd loop forever):

Full solution

function arrayToList(arr) {
    if (arr.length === 0) {
        return null;
    }
  
    var value = arr.shift();

    return {
        value: value,
        rest: arrayToList(arr)
    };
}

console.log(arrayToList([10, 20])); // {value: 10, rest: {value: 20, rest: null}}

That's it! Does that make sense?

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Creating R list as config object in JavaScript style

분류에서Dev

Javascript: Remove object from array on function call to object

분류에서Dev

Creating a new instance of a Javascript object

분류에서Dev

Creating List from Linq filter

분류에서Dev

How to replace values in an object with values from a list in Javascript?

분류에서Dev

count 'last children' from any point in javascript object/array structure

분류에서Dev

Get valid python list from string (javascript array)

분류에서Dev

Pass an object into an array in JavaScript

분류에서Dev

Creating eset object from preprocessed expression matrix?

분류에서Dev

Creating a scala object from java: The constructor is undefined

분류에서Dev

Remove object from array

분류에서Dev

Creating a Comma Seperated List from a subquery in SQL

분류에서Dev

Creating a boolean list from sublists . Python 2.7

분류에서Dev

creating an array from the value of a single cell in excel

분류에서Dev

Javascript 문자열을 Object (list / array)로 변환

분류에서Dev

Object insert issue in JavaScript array

분류에서Dev

Sort javascript object with array as value

분류에서Dev

Javascript - Defining a Object with Array Properties

분류에서Dev

Keep getting [object, Object] from array for $.each

분류에서Dev

Remove object from JSON array

분류에서Dev

How to access attributes of php object inside a array of php objects from javascript

분류에서Dev

Accessing variable from JavaScript object

분류에서Dev

Javascript - count and remove from an object

분류에서Dev

Returning values from an Object in Javascript

분류에서Dev

Fixing 'Creating default object from empty value' warning in PHP

분류에서Dev

Creating a composite object from two other core data objects

분류에서Dev

ErrorException: Creating default object from empty value in Controller

분류에서Dev

Creating a single column vector from a list column in R

분류에서Dev

Creating a list/vector from first column od multiple data

Related 관련 기사

  1. 1

    Creating R list as config object in JavaScript style

  2. 2

    Javascript: Remove object from array on function call to object

  3. 3

    Creating a new instance of a Javascript object

  4. 4

    Creating List from Linq filter

  5. 5

    How to replace values in an object with values from a list in Javascript?

  6. 6

    count 'last children' from any point in javascript object/array structure

  7. 7

    Get valid python list from string (javascript array)

  8. 8

    Pass an object into an array in JavaScript

  9. 9

    Creating eset object from preprocessed expression matrix?

  10. 10

    Creating a scala object from java: The constructor is undefined

  11. 11

    Remove object from array

  12. 12

    Creating a Comma Seperated List from a subquery in SQL

  13. 13

    Creating a boolean list from sublists . Python 2.7

  14. 14

    creating an array from the value of a single cell in excel

  15. 15

    Javascript 문자열을 Object (list / array)로 변환

  16. 16

    Object insert issue in JavaScript array

  17. 17

    Sort javascript object with array as value

  18. 18

    Javascript - Defining a Object with Array Properties

  19. 19

    Keep getting [object, Object] from array for $.each

  20. 20

    Remove object from JSON array

  21. 21

    How to access attributes of php object inside a array of php objects from javascript

  22. 22

    Accessing variable from JavaScript object

  23. 23

    Javascript - count and remove from an object

  24. 24

    Returning values from an Object in Javascript

  25. 25

    Fixing 'Creating default object from empty value' warning in PHP

  26. 26

    Creating a composite object from two other core data objects

  27. 27

    ErrorException: Creating default object from empty value in Controller

  28. 28

    Creating a single column vector from a list column in R

  29. 29

    Creating a list/vector from first column od multiple data

뜨겁다태그

보관