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

Here’s another example taken from the narrative of “The Sieve of Eratosthenes” (a Pro offering, I believe, so you may not be able to access it). Note the return value…

``````const sieveOfEratosthenes = (limit) => {
// Handle edge cases
if (limit <= 1) {
return [];
}
// Create the output
const output = new Array(limit + 1).fill(true);
// Mark 0 and 1 as non-prime
output[0] = false;
output[1] = false;

// Iterate up to the square root of the limit
for (let i = 2; i < Math.pow(limit, 0.5); i++) {
if (output[i] === true) {
// Mark all multiples of i as non-prime
for (let j = Math.pow(i, 2); j <= limit; j = j + i) {
output[j] = false;
}
}
}

// Remove non-prime numbers
return output.reduce((primes, current, index) => {
if (current) {
primes.push(index);
}
return primes
}, []);
}
``````

Above we have an array of truth values, either true or false that has be sieved over and transformed from all true, to only some true (the ones that don’t get re-marked). In the return expression we cache only the indices where the value is true. That gives us our list of primes up to the limit.

1 Like

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

``````array.join(' ')
``````

we can use join instead of reduce.

1 Like

That much is moot. The above simply demonstrates the use of `.reduce`. We’re not confined to one way or another, and obviously `.join()` makes much more sense in this case.

Where `.reduce()` could prove useful is if there was some logic being applied in the joining process since it has a callback function that can be expanded for that purpose.

I checked it. .reduce() is good for joining strings like ’ and ’ at last concatenaton

1 Like

Not a professional but I think it’s very useful for many score systems alike this one:

``````// vvv a array for tracking how much money you got in each month vvv
const moneyMonths = [3425, 4582, 7542, 7572, 3545, 7645, 4356, 3784, 6855, 8561, 2306, 5020];
const totalMoneyEarned = moneyMonths.reduce((a, b) => {
return a + b;
});

console.log(totalMoneyEarned) // Output is the total of moneyMonths: 65193
``````

Parenthesis Outside of the code block ? I didn’t get you ?

As the OP said, what’s the real world application of doing it like this that may make a difference? If I wanted a sum of the array + 10, I’d probably NOT use reduce, but… newSum = newSum + 10 (a bit easier to see in the code why 10 is being added, vs buried at the end of a function with reduce. ) – yes, yes, some may not and getting used to the function. I understand that. But real world? Who would?

Part the second… Why does the second argument (which for the exercise, add 10) in reduce get added in to the process as the 1st step: “Start from 10 and then do the math” and not “add everything up and then +10 after getting the sum of the array”?

Short of delving into more complex examples of `reduce()`, we will find it in use in some rather esoteric ways, though it is demonstrated on a simple array sum. What if that sum is a series (a summation of a sequence of function returns) such as a sine or cosine?

Bottom line, in the learning phase we are wont to question the value of a given concept based upon our naiveté. That’s not wrong, but failing a useful answer we should never jump to the conclusion that we have a better way.

This took a couple of hours to write and still needs type checking, and such but works correctly for radian angles. Note the ways in which `reduce()` is used.

sine/cosine series with 'reduce()' - Replit

There are a number of helper functions, `mul`, `add`, `range`, `factorial` and `print` (for ease) with the main function being, `sine()` and its immediate dependency, `computeTerm()` which evaluates the general term for a given `n` along with an angle. The angle is given to `sine()` and `n` is initially zero, then increments by 1 each term to generate the series. The value returns as a signed float.

`mul` and `add` are self-explanatory but `range` deserves some explanation. It is not a complete range function in the overall sense (think Python’s `range()`) but it fills in for our needs by being able to produce an array that either starts with `0` or any other initial value, then generates the next integer in the sequence.

`````` > range(0, 10)
<- [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
> range(1, 10)
<- [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
``````

The first one is used in the `sine()` function to give us values for `n`, as in t(n); the second is used by the `factorial()` function to give us an array of values from 1 to n, inclusive.

Both uses of `reduce` are very simple since we do all the heavy lifting by other means, but they are hugely influential in how they do not distract from what the real code is doing. I’m sure this is not the best example, yet, but I had a tonne of fun writing it.

``````const computeTerm = (x, n) => {
const a = (-1) ** n
const b = 2 * n + 1
const c = factorial (b)
return (a * (x ** b)) / c
}
const sine = x => {
return range(0, 10).map(p => computeTerm(x, p)).reduce(add)
}
print (sine(1), sine(Math.PI / 4))          //  own function
print (Math.sin(1), Math.sin(Math.PI / 4))  //  Math module
``````
``````0.8414709848078965 0.7071067811865475
0.8414709848078965 0.7071067811865475
``````
2 Likes

In this case, .reduce() multiplies firstly 1x2 then the answer of (1x2) multiplied by 3 then the answer that multiplied by 4 etc…

Without the return the iterator will have no effect.

``````const x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const y = x.reduce(function (a, b){
a + b
})
console.log(y)    //  prints, undefined
``````
``````const x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const y = x.reduce(function (a, b){
return a + b
})
console.log(y)    //  prints, 45
``````

Given that we have concise body functions at our disposal for use in the callback,

``````const x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const y = x.reduce((a, b) => a + b)  // implicit return
console.log(y)    //  prints, 45
``````
1 Like

Oh yeah… didn’t notice that there was no return. Thank you for the clarification!

1 Like

Such a perfect explanation thank you.

1 Like

This makes a lot of sense and the .reduce() method feels like I was learning algebra or something similar. I’m not a math person lol. But it took me a while to see the pattern.

1 Like

My reaction to all the explanations to reduce. Lol This can dive deep.

3 Likes

Hello, please i need some help grasping the application of `.reduce` applied in the code below.

Code Snippet from MDN

``````const arr = [1, 2, [3, 4, [5, 6]]];

// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};

flatDeep(arr, Infinity);
// [1, 2, 3, 4, 5, 6]
``````

Great response!
You made my mind click, Thx!

the parenthesis are outside the code block b/c the code itself is an argument to the .reduce method which wraps the entire call back function in parenthesis.

Hope that helps.

1 Like

And when one gets their head around that will begin to understand higher order functions.

I am new to coding, and late to join this discussion. In case it would help anyone, I’ll share this example of how you can use simple code to use reduce() for mathematical applications.

/* simple application that will calculate factorials based on user input. if you don’t know what a factorial is, in math, 5 factorial would be written as 5!, and 5! = 5 * 4 * 3 * 2 * 1 */

let factorial = prompt(“What number do you want a factorial for?”)
/* codecademy hasn’t taught “prompt” in the JS lessons so far, but it’s great to know for writing simple practice apps so you can get user input. what it does is make a dialogue box appear that asks for user input, and then the user input gets assigned to the variable “factorial” */
;
let array = ;
//empty array that will get loaded with the numbers necessary for the factorial calculation

while (factorial > 0) {
array.push(factorial);
factorial–;
}
//the while loop loads the numbers needed for the calculation into the array

let answer = array.reduce((val1, val2) => {
return val1 * val2;
})
//the reduce function multiplies all the values in the array and returns the factorial value stored in the “answer”

alert(answer); /* “alert” hasn’t been taught yet in the lessons. what it does is make a dialogue box appear with the content inside the parenthesis–you can put a string or a string template rather than a variable, or a concatenation of stuff. if you use “alert” rather than “console.log” then people who don’t code can make use of the program. */

Granted, I have absolutely no use for calculating factorials, and I wrote this program for practice, but maybe it’s helpful for beginners like me to see how you can use reduce() in a simple program that will perform calculations for you based on user input