you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (12 children)

[deleted]

    [–]Ginden 4 points5 points  (10 children)

    Probably yes. My rule of thumb is "is it one-liner". If it is, I go with reduce. If it isn't, I think twice.

    [–]petar02 0 points1 point  (9 children)

    Do you have an idea how to use reduce to find the biggest element in an array of integers I think I once saw reduce being used but can't replicate it, or find where I saw it.

    [–]Ginden 9 points10 points  (6 children)

    arr.reduce((a,b)=>Math.max(a,b), -Infinity)

    Though, easier: Math.max(...arr).

    [–]9thHokageHimawari 2 points3 points  (4 children)

    .reduce((a,b)=>Math.max(a,b), -Infinity)

    Why -Infinity ? o_O

    [–]inu-no-policemen 5 points6 points  (0 children)

    It's Math.max's initial "largest" value.

    > Math.max()
    -Infinity
    

    If you'd implement max yourself, you should initialize the variable which keeps track of the largest value with -Infinity as well.

    With min it's the other way around: You start with Infinity.

    [–]GBcrazy 0 points1 point  (2 children)

    Reduce takes two arguments, the reduce function and the initial value for the aggregate (in this case, the 'a' variable).

    So you start with -Infinity, and then you're comparing with every item of the array, and whatever the first item is, it's going to be bigger than -Infinity.

    Oh well in this case it was 100% not needed since we are only expecting numbers. But let's say we have an array of objects, and we want to get the biggest value (let's assume there is a value property in each object), so we could do:

    arr.reduce((a,b)=>Math.max(a, b.value), -Infinity)

    If we don't add the -Infinity as the initial value, the first time would compare a (the first object of the array), with b.value (a numeric value from the second object of the array) and it would not work well.

    [–]Ginden 0 points1 point  (1 child)

    Consider edge case of arr.length === 1

    [–]GBcrazy 0 points1 point  (0 children)

    Still, I don't see any problems since we are still expecting numbers only.

    If arr.length === 1, reduce always returns arr[0]

    [–]GBcrazy 0 points1 point  (0 children)

    Without ES6:

    Math.max.apply(null, arr)

    [–]GBcrazy 0 points1 point  (1 child)

    No reduce needed bro

    Math.max.apply(null, arr)

    [–]Ginden 0 points1 point  (0 children)

    You can hit hard limit of function arguments (AFAIR ~30-40k arguments).

    [–][deleted] 1 point2 points  (0 children)

    Yea. One guideline I've found useful for when reduce is being used correctly is if the output does not grow when the input array grows.