I am new to recursion. I can flatten an array and return as a normal array, but if I want to flatten the array and store it inside an object and return the value, for some reason I am losing the value of the previous result, it would be great if you could help me out. PS: I am able to do this by sending the result as an argument every iteration, but I want to do it this way so..
const flatten = (nums) => {
result = {
number: [],
};
console.log(result);
for (let num of nums) {
if (Array.isArray(num)) {
result = {
...result,
...flatten(num),
};
} else if (typeof num === "number") {
result = { ...result, number: [...result.number, num] };
}
}
return result;
};
console.log(flatten([[1, 2], [3, [6, [1, 2, 3]], [4, [5]]], [1]]));
and I even tried this below method, I know i am making some mistake, it's just i am unable to find where exactly
const flatten = (nums) => {
return nums.reduce(
(acc, ele) => {
if (Array.isArray(ele)) {
acc = { ...acc, num: [...flatten(ele)] };
} else {
acc = { ...acc, num: [...acc.num, ele] };
}
return acc;
},
{ num: [] }
);
};
expected output:-
result={
number:[1,2,3,6,1,2,3,4,5,1]
}
or
{
number:[1,2,3,6,1,2,3,4,5,1]
}