How to use reduce() in JS

Sometimes you need to quickly add a few numbers without writing too much extra code for such a simple calculation. You can of course you can use any type of loop but in JS there's a simplier way by using the reduce() function.

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value

Note: reduce is helpful for a short list of numbers!

Pretty self-explainatory.

 
Let's take an example and try to calculate average pay in Albania 2021.
 
1.First create a simple React app and install a lib called Papaparse from NPM as we're gonna be feeding data from a .csv file.
 
2.Documentation of Papaparse shows how to easily make use of the lib to import files into our code

calculateAveragePayInAlbania( list ) is our custom function

 
3.This is what a record looks like now for us. Pay in 7th element.
 
4.Our logic using reduce()

Here, PAGAT_2021 is the .csv file we previously imported using Papaparse in JSON format, for easy of manipulation.

reduce(a, b)... will add the first two items in list, then their sum to the third and so on.

 

We're gonna have to do some clearing.

" 70,000.00 " as a value doesnt help JS so I'm gonna remove the spaces and commas. => 70000.0

Now we can successfully add the values one by one, with the help of reduce.

After hitting Run, calculating took some time on my computer (~2 min), quite slow, but that's reasonable as there is too much money in this code.

 
So there it is. Our reduce function finished running and according to it, the average pay in Albania 2021 is: 46,433.35 Lek.

Sounds about right, but err.. cmon.. its Javascript .. and math..

 

Thank you for your time. Have a nice time this end of year.

:)

Comments

Let's Talk