Member-only story

How To Use The Reduce Method In Javascript

Javascript methods — Reduce

Otutu Chidinma Janefrances
4 min readApr 1, 2024
Photo by Gabriel Heinzer on Unsplash

The reduce method processes each element of an array (from left to right) to produce a single output value.

It can be used to sum numbers, flatten nested arrays, or group objects based on a shared property.

Reduce Syntax

arr.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)

Let’s break down each of these:

  • callback: A function to execute on each element in the array (except for the first element if no initialValue is provided), taking four arguments:
  • accumulator: The accumulator accumulates the callback’s return values; it’s the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
  • currentValue: The current element being processed in the array.
  • currentIndex (Optional): The index of the current element being processed in the array.
  • array (Optional): The array reduce was called upon.
  • initialValue (Optional): A value to use as the first argument to the first call of the callback. If no initial value is provided, the first element in the array will be used as the initial accumulator value…

--

--

Otutu Chidinma Janefrances
Otutu Chidinma Janefrances

Written by Otutu Chidinma Janefrances

Software Developer | Content Creator| Writer

No responses yet