5

I'm reading through Eloquent JavaScript and at the end of Chapter 4 it challenges you to turn an array into a list i.e.

[1, 3, 3] --> {value: 1, rest: {value: 2, rest: {value: 3, rest: null}}};

And I do not think I'm understanding the concept.

It suggested iterating backward through the array, so I had tried:

function arrayToList(array) {
    let list = {};
    for (let i = array.length -1; i > array[0]; i--) {
        list += ("value:" + i + ", rest: null");
    }
    return list;
}

console.log(arrayToList([1, 2, 3]));

And this logs out:

[object Object]value:2, rest: null

As you can see I'm not understanding how to create "nested" objects (lists) with iteration. Can someone please explain this to me?

1
  • 1
    It doesn't turn an arra into a list, in turns an array into an object representing an array
    – Nino Filiu
    Apr 19, 2019 at 19:04

5 Answers 5

4

You need to start with null as first list value.

Then you need to iterate through the elements with the index from the last to zero and assign a new list object with an actual value from the array and the former list as rest.


What you have tried, is a wrong iteration by checking an element and by starting with a wrong value which is later converted to a string by adding strings, instead of an object.

function arrayToList(array) {
    let list = null;
    for (let i = array.length - 1; i >= 0; i--) {
        list = { value: array[i], rest: list };
    }
    return list;
}

console.log(arrayToList([1, 2, 3]));

1
  • 1
    Oh I see, so you can just declare the value as value: and the rest as rest: - you don't need to put quotes around them, since they're object properties, if I understand correctly. Apr 19, 2019 at 19:14
3

I think you have good answers about why you have a problem in your code, but just in case you're interested, this is a really pretty use case for reduceRight()

let a = [1, 3, 3]
let l = a.reduceRight((rest, val) => ({val, rest}), null)

console.log(l)

It does more-or-less the same thing your code does — starts with null and loops backward through the list while compiling the previous results into the rest property.

1
  • 1
    Good one, is nice to keep that method always present.
    – Shidersz
    Apr 19, 2019 at 19:16
1

With the forward iteration, you can do something like this. Iterate over the array, on each iteration define nested object until reaching last element and when reached last define property as null.

let data = [1, 3, 3];

let res = {};
for (let i = 0, obj = res; i < data.length; i++) {
  obj.value = data[i];
  obj = obj.rest = i < data.length - 1 ? {} : null;
}
console.log(res)

1
  • Nope, it should be initialized with null, not {}
    – Nino Filiu
    Apr 19, 2019 at 19:06
1

This could be a problem well suited for a recursive approach:

function arrayToList(array)
{
    if (array.length <= 0)
       return null;

    return {value: array[0], rest: arrayToList(array.slice(1))};
}

console.log(arrayToList([1, 2, 3]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

1

You can greatly simplify your code.

There are two cases: either the array is empty, in this case cast to null, either it's not, in this case only the first value matter, the rest can be handled recursively on the rest of the array. It's a one liner.

const converter = arr => arr.length ? ({value: arr[0], rest: converter(arr.filter((_,i) => i>0))}) : null;      
console.log(converter(['a', 'b', 'c']));

Not the answer you're looking for? Browse other questions tagged or ask your own question.