1

I am trying to convert an array to list(containing objects) and first object is connected to next pair value.

This is what I have done so far:

var myArray = [1,2,3] ;
function arrayToList()
{
    var myList = Object.keys(myArray).map(function(key){

        return { value: myArray[key],rest:myArray[key]}    

    });
    console.log(myList);
}
arrayToList(myArray); 

This should return Like this:

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

, when given an array of [1,2,3]

3
  • instead of rest being rest:myArray[key], call arrayToList() again - but give an offset so you will eventually stop recursing. Commented Oct 17, 2017 at 15:07
  • Object.keys(myArray) makes no sense since you have an array, not an object. Commented Oct 17, 2017 at 15:15
  • What would you want the output to be when the array is empty? Should it just return null? Commented Oct 17, 2017 at 19:50

2 Answers 2

3

Use Array#reduceRight

function arrayToList(arr) {
  return arr.reduceRight((rest, value) => ({ value, rest }), null);
}

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

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

2 Comments

It is working but when you expand the 2nd value in browser it disappears and all you can see it value 1 and value 3. One more thing if you want to do the reverse for List to Array what one can do ? The output for the first one is {value: 1, rest: {…}}rest: rest: rest: nullvalue: 3__proto__: Objectvalue: 2__proto__: Objectvalue: 1__proto__: Object
@NaumanMughal The value doesn't disappear. The browser displays it below the expanded object. If you want, you could do a console.log(JSON.stringify(arrayToList([1, 2, 3]))); for more clarity.
1

This lends itself well to a simple 1-line recursive function (especially nice with es6):

function tolist([value, ...rest]) {
      return {value, rest: rest.length ? tolist(rest): null}
}

console.log(tolist([0, 2, 3, 4]))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.