I am having trouble converting a list of objects to array. On the second function listToArray I am trying to loop through properties and check whether the value is number or not. In case of a number I just push it to the empty array, but if it's not then I am trying recursion with a property as an argument. I'm getting an empty array, help me please. NOTE: No brute force solutions, please. Like, list.value and list.rest. Thank you!
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray(list) {
let array = [];
for (let i in list) {
if(typeof list[i] == "number") {
array.push(list[i]);
} else if(typeof list[i] != "number") {
return listToArray(list[i]);
}
}
return array;
}
console.log(arrayToList([10, 20]));
Result: {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
Result: []
When you do
return listToArray(list[i]);
you're ignoring the current iteration's value and only returning the value in the nested structure. You're also iterating over all properties unnecessarily (and returning before going on to the second) instead of referencing the exactly 2 properties that will exist.
Extract the value property, extract the recursive value if it exists, and return an array of those two together.
If the argument may not be an object, check that too before extracting values from it.
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray(list) {
if (!list) return [];
const { value, rest } = list;
if (!rest) return [value];
return [value, ...listToArray(rest)];
}
console.log(listToArray(arrayToList([10, 20, 30])));
or, with a default recursive argument instead of spreading:
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray(list, array = []) {
if (!list) return array;
array.push(list.value);
return listToArray(list.rest, array);
}
console.log(listToArray(arrayToList([10, 20, 30])));