I am practicing recursion and have written this function:
var bigArray = ['a', ['b', ['c', ['d', {a:'e'}]]]];
var results = [];
function bagger293(bigArray){
for (var item in bigArray){
if (Array.isArray(bigArray[item])){
bagger293(bigArray[item]);
}
else if (typeof bigArray[item] === 'object'){
bagger293(bigArray[item]);
}else{
results.push(bigArray[item]);
}
}
}
bagger293(bigArray);
console.log(results);
I simply want the function to push any single value to an array, and search deeper if it is an object or array. Oddly, my function returns this:
[ 'a',
'b',
'c',
'd',
'e',
'd',
'e',
'c',
'd',
'e',
'd',
'e',
'b',
'c',
'd',
'e',
'd',
'e',
'c',
'd',
'e',
'd',
'e' ]
I assume it is because of my way of specifying
bigArray[item] but don't know why exactly.
expected result:
['a', 'b', 'c', 'd', 'e']