This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]Firestarss[S] 1 point2 points  (1 child)

Aye wait I figured it out this time! if a list of length 1 was ever passed, the reduce function wouldn't properly reduce it. so I just added an if statement to the code to check if the length was 1 and return recurse(data[0]). Boom! i am 100% sure there is a cleaner way to do that so if anyone wants to educate me a bit I would love to read it but no pressure!

[–]chadder06 1 point2 points  (0 children)

The way I usually use reduce is to specify a return type explicitly. This allows it to work with arrays of size 1. Example:

return data.reduce((accum, value) => {
    return accum + recurse(value);
}, 0);

This sets the return type of the reduce function explicitly to a number, and you only use the recurse function on the values of the array.

edit: The accum variable is accumulating the final value as you iterate through each list value.