What is a real world application of `.reduce()`?

What would be a real world example for using this method. I understand what its doing but it I guess i’m trying to picture what I’d use it for.

For a lot of these excessive I like to think about how i can apply to a real world application

15 Likes

Explanation of javascript’s reduce() with a real world use case

As we see, this method is not just for numeric computation.

This will seem a silly way to compute factorial…

[1,2,3,4,5,6,7].reduce((a, b) => a * b)    // 5040

but it is short and sweet. And this would seem a strange way to join strings…

array = ['A', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'];
array.reduce((a, b) => a + ' ' + b)
// "A quick brown fox jumps over the lazy dog"

Neither is very real world when compared with the example given in the article. Perhaps in your reading you will find some other examples. Please do share!

25 Likes

Accumulator acts as a running total.
I think it would be helpful to calculate the cumulative sums of sales metric for each day.
For exmaple , sales_jan = [200,300,400,500, 100].
Day 1: $200
Day 2: $500
Day 3: $900
and so on…

21 Likes

I think it’s really a good and concise method to perform numeric computation and as well as concatenation on all the elements of an array, looking at the examples @mtf gave.

2 Likes

Can someone explain to me why I am putting the parenthesis outside of the code block? I think I missed something. See below.

const newNumbers = newSum.reduce((accumulator, currentValue) => {
return accumulator + currentValue
})

The parens are the delimiters of the argument for the reduce method.

iterable.reduce(callback)

The callback may be a literal function…

iterable.reduce(function (a, b) {
    return a + b;
})

or,

iterable.reduce(f(a, b) => {
    return a + b;
 })

or,

iterable.reduce((a, b) => a + b)

or, we can write the callback as a standalone function that can be accessed by the rest of the program (optimal)…

a_add_b = (a, b) => a + b;

iterable.reduce(a_add_b)

It should be noted that iterable above is an array.

Let’s play with a number in which we wish to add the digits…

a = 123456789

s = a.toString().split('').reduce((m,n) => +m + +n)

console.log(s)    //  45
4 Likes

Great code, though how does this syntax work?

Have never seen this before. Why are there + signs before m and n?

1 Like

The + is one of the unary operators which in some cases can be counted upon to coerce an object to a Number. It comes with a disclaimer in as much as it is not a silver bullet.

Our data in the array is String and we know the characters are number representations that can be coerced to Number with certainty. It’s a controlled situation.

+m + +n

takes,

'1' + '2'  // would result in '12'

and turns it into,

1 + 2      // which gives 3

Taking this a bit further…

 > +[]
<- 0
 > +{}
<- NaN
 > +[1]
<- 1
 > +[5]
<- 5
 > +[2, 3, 4]
<- NaN
 > +{1}
 X Uncaught SyntaxError: Unexpected token '}'
 > +{a: 1}
<- NaN
 > +"two"
<- NaN
 > +"42"
<- 42
 > +NaN
<- NaN
 > +true
<- 1
 > +false
<- 0
 > +null
<- 0
 > +undefined
<- NaN
9 Likes

Sorry this is off topic, but why don’t your exercises use the backtick style of printing stuff to the console? For example, I always see your codes like this:

console.log('My name is ' + myName + '.')

Why don’t you use this instead: console.log(`My name is ${myName}.`)

Is there a reason we should still use the older style?

Excellent stuff, thanks for sharing, TiL.

Not a particular reason, no, but it may be that template literals have not been taught, or perhaps the lesson material was created before they came into regular use but the author. At any length, we need to understand concatenation and nothing beats practice.

2 Likes

Agreed. It’s also fun to say the word “concatenate.” :stuck_out_tongue_closed_eyes:

Seriously, though, you will likely find yourself in situations where you are reading code written by other people and it’s good to be familiar with different styles of doing the same thing.

On another side note, I find template literals somewhat slow to type–I’m not used to reaching for that backtick character, then I have to use the dollar sign and curly brackets. I find myself tempted to concatenate, and not just because I like the word. In some ways it seems more convenient.