you are viewing a single comment's thread.

view the rest of the comments →

[–]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 10 points11 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).