I am trying to nest a recursive function in an Array.reduce call.
But the following does not work for the third instance only
const i1 = {'local': [['a','b']]};
const i2 = {'local': [['c','d']], 'recursive': []};
const i3 = {'local': [['c','d']], 'recursive': [{'local': [['e','f']]}]};
function reduce(current, result = []) {
if(current.hasOwnProperty('local'))
result.push(...current.local);
if(current.hasOwnProperty('recursive'))
result = current.recursive.reduce(reduce, result);
//'result =' should be optional, but yields a wrong answer anyway
return result;
}
console.log(reduce(i1));
console.log(reduce(i2));
console.log(reduce(i3));
So instead of calling reduce I tried the following loop
for(var i = 0; i < current.recursive.length; ++i)
result = reduce(current.recursive[i], result);
//'result = ' is optional for it is passed by reference
and it works. Being new to JavaScript, I am certain of missing a key feature here, so could you explain ?
Output for the third instance should be
[ [ 'c', 'd' ], [ 'e', 'f' ] ]
but is
{ local: [ [ 'e', 'f' ] ] }
or
[ [ 'c', 'd' ] ]
when result = is removed.
Array#reduce? why do you need a recursion? the data base is not the same and the signature ofArray#reduceneeds the second parameter for the element.Array#reduce, mixing assignments and functional style, and naming your own functionreduce. But I think the main issue is that your order of arguments is wrong. It should befunction reduce(result, current).reducetakes the accumulator first and the element second.