#2 Functional approach: Reduce

Ricardo Luz
2 min readDec 11, 2017

--

One of the most useful and beautiful things that Javascript offer is reduce, this method can help you to solve a lot of problems in several situations and help you to avoid unnecessary loops, this also became your code smaller and more functional.

A reduce function can be used to return a single result from an array (e.g. the sum of field) or can be used to generate other array or object.

This is the structure of a reduce function:

Where:

The accumulator is the result of this reduce when the loop is ended, depending on your logic it can be the average of the values of the array, the concatenation of fields in an array and even another array.

Field is the interator of your array, with this you can retrieve your values and use this in your logic

accumulatorInitialValue is an optional parameter but very useful, with this you can define the initial value of your accumulator and define your accumulator as an array or a string or an object when it is omitted the default value became the first value in your array.

Some examples

If you have an array with some numbers and you want the sum of this numbers:

Looks simple right? this same operation using FOR have a code bigger, let’s take a look:

Using reduce to return another array

This example uses spread operator and template literals if you don’t know what is a spread operator you can read this great David Walsh explanation.

If you want to know more about reduce method the MDN web docs is a good start, also, this Josh Pitzalis article have a great explanation and good examples.

Also, to know more about Javascript I recommend these books:

  • You Don’t Know JS Serie by Kyle Simpson (My favourite)
  • Eloquent JS by Marijn Haverbeke
  • Head First Javascript by Michael Morrison
  • Secrets of the JavaScript Ninja by Bear Bibeault and John Resig

Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful.

You can connect with me on Twitter: @_rxluz or in my Website.

If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇

--

--