You need to use a recursion here, if you the property is "rest". In addition to get the value use list[property]:
function list_to_array(list) {
const arr = [];
for (const property in list) {
if (property == "value") {
arr.push(list[property]);
} else if (property == "rest") {
arr.push(...list_to_array(list[property])); // call list_to_array on the rest
}
}
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
However, you can shorten the recursion - always add the value. If rest exists, return the call of the function with rest and the current arr. If no rest, return arr:
function list_to_array({ value, rest } = {}, arr = []) {
arr.push(value);
return rest ? list_to_array(rest, arr) : arr;
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
A simpler solution would be to use a while loop, and take the rest property value on each iteration:
function list_to_array(list) {
const arr = [];
let current = list;
do {
arr.push(current?.value);
} while(current = current?.rest);
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
Answer from Ori Drori on Stack OverflowWhat can I convert to an array?
Can I remove duplicates from my list?
Does this site store my data in the cloud?
You need to use a recursion here, if you the property is "rest". In addition to get the value use list[property]:
function list_to_array(list) {
const arr = [];
for (const property in list) {
if (property == "value") {
arr.push(list[property]);
} else if (property == "rest") {
arr.push(...list_to_array(list[property])); // call list_to_array on the rest
}
}
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
However, you can shorten the recursion - always add the value. If rest exists, return the call of the function with rest and the current arr. If no rest, return arr:
function list_to_array({ value, rest } = {}, arr = []) {
arr.push(value);
return rest ? list_to_array(rest, arr) : arr;
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
A simpler solution would be to use a while loop, and take the rest property value on each iteration:
function list_to_array(list) {
const arr = [];
let current = list;
do {
arr.push(current?.value);
} while(current = current?.rest);
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
I suggest to avoid recursion here since with big lists that could overflow the stack easily. A simple while loop would do the task:
function list_to_array(list) {
const arr = [list.value];
while(list = list.rest) arr.push(list.value);
return arr;
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(...result);
Take the array content as string like this in a variable:
var words = "greet campaign coffee care revise ridge pilot full prison wrestle account dictionary start giant fast monarch patrol bear motif detective trouser title act speaker pursuit penny appear ballet agreement welcome similar sensation strong fog limited implicit nursery neighborhood infinite refund double achievement ample socialist intensify nomination visit drag retiree mislead situation credit oil clarify conscience war sow suitcase fixture worth fuss remain moment frighten spider breathe install interactive allow deadly cabin restless service rise integrity artist short circuit perception listen arrangement patience creep landscape stain citizen microphone nose bullet view category reign horizon news social reliable passion stroll constitutional adult city";
and then, write
var wordsArray = words.split(' ');
console.log(wordsArray);
That's magic of JS
First thing I want to say is that your syntax is incorrect. If you are trying to express a string, please use the format - var a = "fox hen lol haha";
If you meant your variable words to be a string, and each word to be separated by a space, I have the solution to your problem.
var words = "bla bla bla your words here";
var arrayOfWords = []; // Create the array to store words
arrayOfWords = words.split(" ");
And it's done. The array arrayOfWords contains all the words from the string as individual array objects.
If you are still confused, please comment below.
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]));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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.
» npm install list-to-array