DEV Community

Cover image for Understanding Custom Array.prototype.reduce and Its Implementation
Santosh Bharti
Santosh Bharti

Posted on

3 1 1 1

Understanding Custom Array.prototype.reduce and Its Implementation

What is Array.prototype.reduce?

The reduce method executes a reducer function (provided by you) on each element of the array, resulting in a single output value. The reducer function takes four arguments:

1.Accumulator: The accumulated value previously returned by the last invocation of the callback, or the initialValue if supplied.
2.Current Value: The current element being processed in the array.
3.Current Index: The index of the current element being processed.
4.Source Array: The array on which reduce was called.

array.reduce(reducerCallbackFn,initialValue)

Lets start with basic implementation of reduce

Image description

Initializing the Accumulator

let accumulator=initalValue!==undefined?initalValue:this[0]

The accumulator is the value that will be updated with each iteration of the loop. If an initialValue is provided, it is used as the starting value for the accumulator. otherwise, the first element of the array (this[0]) is used as the initial value.

Determining the Start Index

let startIndex = initialValue !== undefined ? 0 : 1;

If an initialValue is provided, the loop should start from index 0 otherwise, it should start from index 1 because the first element is already used as the initial value for the accumulator.

Iterating Over the Array

Image description

The loop iterates over the array, starting from the appropriate index. For each element, the callback function is called with the following arguments:

1.Accumulator: The current accumulated value.
2.Current Value: The current element (this[i]).
3.Current Index: The index of the current element (i).
4.Source Array: The array itself (this).

The result of the callback function is assigned back to the accumulator.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
ratnabh profile image
ratnabh

Very well explained!

Collapse
 
karishma_cdd733401f9d48d4 profile image
Karishma

Nicely explained

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

If you found this post helpful, please leave a ❤️ or a friendly comment below!

Okay