Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Eray Kaya
Eray Kaya

Posted on • Edited on

     

How does reduce method works?

In this series i will try to explain how does anunderrated javascript method, reduce, works and how we can use this method.

First let's take a look at how we would write this function if it wouldn't exist natively.

Reduce function followsaccumulator pattern meaning that it tries to reduce the value, which we put into our function, to a single value.

It takes two parameters first one is callback function, second one is the initial value. If we define initial value,accumulator starts equal to the initial value. If not it starts as first element of the array.

functionfakeReduce(){functionreduce(callback,initialValue){letaccumulator;letstart=0;if(initialValue){accumulator=initialValue;}else{accumulator=this[0];start=1;}}
Enter fullscreen modeExit fullscreen mode

After we need to define our callback function which takes 4 parameters: accumulator, current value, index number and array. At eachfor iteration callback function runs again until loop is over and our return value is accumulator.

functionfakeReduce(callback,initialValue){letaccumulator;letstart=0;//**this** keyword in this function scope points to array which reduce method is used onif(initialValue){accumulator=initialValue;}else{accumulator=this[0];start=1;}for(leti=start;i<this.length;i++){accumulator=callback(accumulator,this[i],i,this);}returnaccumulator;}
Enter fullscreen modeExit fullscreen mode

Right now missing part of our function is error handling but we will not get into that. Our main goal here is to understand how does reduce method works.

In next post of this series i will show some examples how we can use reduce for more complex tasks rather than just summing up numbers of an array.

See you in next post...

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Frontend Lead at Tokensuite
  • Joined

More fromEray Kaya

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp