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

20 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!

33 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…

27 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.

3 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
11 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.

Hi Mtf, thanks for your details but one question a bit silly : how come the output of this :[1,2,3,4,5,6,7].reduce((a, b) => a * b) is 5040 ?

I understood the calculation is 1*2 + (1+2)*3 + (1+2+3)4 etc… but is it thanks to your return ab ? Without this return will it just do a sum as an operator ?

Also can we affirm the main purpose of this function would be to cumul / multiplicate etc… numbers and not be used for the strings ?

Thanks (and sorry for my english :slight_smile: )

The .reduce method can be used in many situations, more commonly with numbers, but also with strings. The choice of operation is up to us. In the example above where we get 5040, that is 7! (7 factorial).

1 * 2 * 3 * 4 * 5 * 6 * 7

So is .reduce() method basically just a the sigma calculator used in Calculus?

Also, it seems like it can only be used for numerical values, is this correct or is there a way to use it with strings as well?

For addition operation, yes. Sigma is a summation of a series. The terms of a series have a proportionality with one another.

In a sense, when the conditions are met, .reduce() can be used to compute a Sigma. However, .reduce() will work on any sequence, however arranged and without any relation between terms.

A series has a general term that describes the proportionality of every consecutive term in the sequence. We see that general term described in the Sigma notation denoting the series.

[2, 3, 5, 7, 9, 11, 14, 15, 17, 20]

The above is a sequence, but not a series. There is no single general term that can describe it. We can still reduce this sequence to a single summation.

[2, 3, 5, 7, 9, 11, 14, 15, 17, 20].reduce((a, b) => a + b)

<- 103

Yes, so long as the operation can be performed.

['a','b','c','d','e','f','g'].reduce((a, b) => a + b)

<- 'abcdefg'

There are other more complex examples on the forums, and online. It is worth the time to study further, but especially be able to emulate this method using conventional iterative approaches. We learn about iterators so we have more tools in our tool box. Just because we have a screw gun doesn’t mean we throw away the hammer.

2 Likes

This example by @ionatan is more advanced and demonstrates the real horsepower of .reduce()

Solution Sharing

Of course, you shouldn’t worry if you cannot understand it, now. Eventually you will be able to write that code for yourself. Set it aside for when you are writing sophisticated code of your own.

I’m not sure I understand the reduce() method fully

I understand that it’s used to reduce an array to a single value. This ‘single value’ can either be a sum of all the elements in an array, a sentence containing all the string elements in an array (concatenated), but what else can you use it for? I read the articles you mentioned and they slightly helped. I understand that you can also add each element to an object (of course there are many ways to obtain a key for the key/value pair)

Can you give me a few more examples and add to what I already know?

In my experience here, I think some of the best examples have been given by @ionatan. Check this local SERP for some good examples.

reduce @ionatan

When I have time I’ll go over it and try to find the ones that stand out.

array.reduce() can be used in a lot of different cases, and as you mention not all of them are mathematical, though it can be used for most operations.

[1000, 100, 10].reduce((a, b) => a/b)    
//  1

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

[[1, 2],[3, 4], [5, 6], [7, 8, 9]].reduce((a, b) => a.concat(b))    
//  [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Wow that article you linked really shows the potential of .reduce - can’t wait to become familiar with the logic behind it!

1 Like