Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert array to list in javascript

function array_to_list(arr) {
  list = null

  for (i = arr.length; i >= 0; i--) {
    list = { value: arr[i], rest: list };
  }

  return list;
}
x = array_to_list([10, 20]);
console.log(JSON.stringify(x));

the output I get is :

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

but I want

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

how can I solve that problem? That is to change the last rest to null instead of another object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To fix your code, set i = arr.length - 1 as the initial value of i. Since arrays have 0 based index, the last item’s index is one less than the arrays length:

function array_to_list(arr) {
  let rest = null

  for (let i = arr.length - 1; i >= 0; i--) {
    rest = { value: arr[i], rest };
  }

  return rest;
}

const result = array_to_list([10, 20]);
console.log(JSON.stringify(result));

I would use Array.reduceRight() to iterate the list from the end, and set the initial value to null:

const array_to_list = arr =>
  arr.reduceRight((rest, value) => ({
    value,
    rest
  }), null)

const result = array_to_list([10, 20]);
console.log(JSON.stringify(result));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading