Skip to content Skip to sidebar Skip to footer

Looping Through Objects And Adding Types

function arrayToList(array) { var list = null; for (var i = 0; i < array.length ; i++) list = {value: array[i], rest: list}; return list; } console.log(arrayToList([

Solution 1:

You are overwriting the value of rest with each of your traversal. I think you should use concept of recursive function to make it fast and accurate.

Please use the following code:

functionarrayToList(array, i){
    if(i == array.length){
        returnnull ;
    }
    return { value: array[i], rest: arrayToList(array, i+1) };
}
console.log(arrayToList([10,20,30], 0));

Here, i represents the index in array. I hope this solves your problem. It worked fine at my system.

The result I got is:

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

Solution 2:

You are doing a console.log() of the returned "list" value. You will not see a "null" in your list.rest because your final value of list would look like this : list = { value: 20, rest : { value : 10, rest : null } }; If you put the following after list = {value: array[i], rest: list}; you will see what I mean : console.log(list.rest) or console.log(list) if you want to see the whole thing.

Also, to answer you question about starting with your first element being 10 and starting at i=0 : the array [10, 20] has an array.length = 2 array[0] = 10 array[1] = 20

Because of this, the last value entered into your "list" will be value = 20. When you do this, you are also storing the value of "list" in "list.rest", which will recursively store whatever your last "list" JSON object was. This could get really messy if you have more than 2 items in the list because with 3, to get to the first, you would have to do list.rest.rest.value -- You probably want to re-think how you're storing your list.

Post a Comment for "Looping Through Objects And Adding Types"