Vilson Castilho

Why should I use reduce?

Hello guys.

Today I would like to share with you the power of "reduce".

I brought some simple examples, that represent very well its potential and also how it can be useful in solving problems encountered during development.

Basically "reduce" is another method present in arrays, which is capable of transforming and extracting information from it.

The "reduce" has five parameters:

  • Accumulator (acc) - Required: This is the accumulated value previously returned from the function or the initial value if it was provided.
  • Current Value (cur) - Required: this is the value of the current array element.
  • Current Index (index) - Optional: this is the index of the current array element.
  • Source Array (array) - Optional: this is the array that was called by reduce.
  • Initial Value (init) - Optional: this is the initial value to be passed to the function. If no initial value is provided, the first element in the array will be used as the initial value of the accumulator and the second element will become the current value.
  • These parameters are passed as follows:

    array.reduce((accumulator, currentValue, currentIndex, array) => {
    //...
    }, initialValue);

    I will leave some examples below, note that in the Terminal we have the results of each interaction (facilitating the understanding of the process behind the interactions) and the final result of the operation, hope you enjoy!

    Thank you and let's code!!! 👨‍💻