Write your own JavaScript reduce() method

Photo by Ben White on Unsplash

Write your own JavaScript reduce() method

·

4 min read

Table of contents

No heading

No headings in the article.

  1. Reduce, is one of the intensively used and important methods of JavaScript. As a beginner, for me learning to use reduce() and then constructing my own reduce() was a big and challenging job. I Know you want to learn it as well. So, worry not, follow along with me.

  2. Before moving further, I suggest we should know about all functionalities and features of reduce() method. Such as, reduce();

       a)  works on an array.
       b) takes two parameters (callBackFunction, initialValue/accumulator)
       c) reduce's callBackFunction takes three parameters (currentValue, indexOfCurrentValue, array)
       d) loop through the whole array and return a single value, according to the passed callBackFunction
       e)  we must take care of the initialValue, and its **typeof **must be given according to the expected output.
    

    Note: From here for initialValue, I'll use a (read accumulator) and c (read current value) for currentValue

  3. Usecases of reduce()

    Sum the elements of an array

// calculating sum of numbers in the array, numArr using reduce()
const numArr = [1,2,3,4,5]
const sumOfnumArr = numArr.reduce((a,c)=>a + c,0)
// expected output 15
// In the above line of code, before closing parentheses, I passed a=0;
// If choose to skip, first element of the array would become a.

Flattens an array or say with reduce, sub-arrays of an array could be turned into one single array

const arrayOfArrays = [[1,2,3],[4,5,6],[7,8,9]]
const array = arrayOfArrays.reduce((a,c)=>a.concat(c))
//expected output : [1,2,3,4,5,6,7,8,9]

Can create a pipeline: In other words, we can use multiple functions on a value by storing these functions into an array.

function increment(input) {
  return input + 1;
}
function decrement(input) {
  return input - 1;
}
function triple(input) {
  return input * 3;
}

const functionsArray = [increament, decrement, triple]
const result = functionsArray.reduce((a,c)=>c(a),5)
//output: 15
// Note: at the return of callBack function of reduce, we have passed a inside c
//c i.e. current value, is a function, as we are applying reduce on an array of functions.
// for this function a i.e. initial value here in this case 5, is acting as an argument

Using reduce() we can get an Object from an array

const tShirts = ["red", "black", "red", "green","red"]
// get an Object, colorOfTshirt as key and their occurrence as value

const obj = tShirts.myReduce((a,c)=>{
  if(a[c]!==undefined){
    a[c]++
  }else{
    a[c] = 1
  }
  return a
},{}) 

// output : {red: 3, black: 1, green: 1}
// Note: we have passed initial value here as an empty object
// because we are expecting our output in the form of object

By now we know enough about reduce, it's time to finally write our own reduce. So, let's begin:

Step1: Declare or define myReduce using prototype

Array.prototype.myReduce = function (){
}
// we have discussed already, that it works on an array. So, we are attaching an Array to it, in the above line

Step2: Pass parameters : callBackFunction and initialValue/accumulator

//note: i'll be using **callBack** for callBackFunction and **a** for initialValue/accumulator


Array.prototype.myReduce = function (callBack, a){
}

Step3: Looping through the array

Array.prototype.myReduce = function (callBack, a){
//using for loop
for(let i=0; i<this.length; i++){
   }
}
//here **this** stands for the Array, which means it uses implicit binding

Step4: Get the current value

//Note: I'll be using **c** for currentValue

Array.prototype.myReduce = function (callBack, a){
for(let i=0; i<this.length; i++){
 let c= this[i]
   }
}

Step5: Time to use callBack

Array.prototype.myReduce = function (callBack, a){
for(let i=0; i<this.length; i++){
   let c= this[i]
   a= callBack(a,c)
   }
}
// we can use a direct or after storing into a variable
// this game of accumulator and current value is important to understand, 
// check this out (https://youtu.be/g1C40tDP0Bk)

Step6: Return the initial value a

Array.prototype.myReduce = function (callBack, a){
for(let i=0; i<this.length; i++){
   let c= this[i]
   a= callBack(a,c)
   }
return a
}

Hurray! myReduce() method is ready to use, now go into your code editor and check it on all the use cases we have discussed above, if it is working in all of them, you are good to go. If you have reached so far, I would say, Bravo... you did great.

photo-1533738363-b7f9aef128ce.avif

Thanks for investing your time here. I'm always open to reviews. So, feel free to connect. My twitter handle