0

I have a function that takes as an argument a list and must return the elements of the list into an array. For example in case of the input:

{value: 1, rest: {value: 2, rest: null}}

The output should looke like:

[1, 2]

This is how I tried to solve it:

function listToArray(list){
  var arr = [];
    for (var node = list; node; node = node.rest) {
        arr.unshift(node);

    }
  return arr;

}
console.log(listToArray({value: 1, rest: {value: 2, rest: null}}));

And the output I get is:

[{value: 2, rest: null}, {
value:  1
rest:   {value: 2, rest: null}
}]

Does anyone know what should I change to make it work?

1
  • using arr.push(node); instead of arr.unshift(node); will change the order of the elements, but still the output format is not the wanted one. Commented Mar 9, 2017 at 12:39

2 Answers 2

2

You were just missing the .value from node.

function listToArray(list){
  var arr = [];
    for (var node = list; node; node = node.rest) {
        arr.unshift(node.value);

    }
  return arr;

}
console.log(listToArray({value: 1, rest: {value: 2, rest: null}}));

Note you might want push instead of unshift.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use recursion to grab all the inner object values.

var obj = {value: 1, rest: {value: 2, rest: null}};
var list = objToList(obj, 'value', 'rest');

console.log(list);

function objToList(obj, valueField, targetField) {
  return objToListInner(obj, valueField, targetField, []);
}

function objToListInner(obj, valueField, targetField, list) {
  if (isObject(obj)) {
    list.push(obj[valueField]);
    objToListInner(obj[targetField], valueField, targetField, list)
  }
  return list;
}

function isObject(obj) {
  return obj !== null && typeof obj === 'object';
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}


A bit of code golf. ;)

let obj  = {value: 1, rest: {value: 2, rest: null}},
    list = objToList(obj, 'value', 'rest');

console.log(list);

function objToList(o, v, t, l) {
  return o ? objToList(o[t], v, t, (l||[]).concat(o[v])) : (l||[])
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.