How to write higher order function in javascript feat. map, filter, reduce

How to write higher order function in javascript feat. map, filter, reduce

Higher order function are nothing but a function that accpect a function as a parameter, map, filter, reduce are Array based functions.

Map

Map function iterate on the array and perform some set of instruction on the array element and returns the output according to the instruction passed in the function, it is very similar to running a basic for loop, map function runs on a array and return a new array with same size, in the below example we are iterating on the array and multiplying every element of it with 10 and as a result we are getting a new array with respective result.

let arr = [2, 4, 6, 8];
let ansArr = arr.map((element)=>{
   return element * 10; 
})
console.log(arr); // [ 2, 4, 6, 8 ]
console.log(ansArr); // [ 20, 40, 60, 80 ]

Filter

Filter function iterate on the array and return a array on basis of filter function, you may be iterating on a array of size 5 and it may return a array of size 3 because it is filtering the element which donot pass the condition, In the below example we are filtering out the even numbers.

let numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let evenArr = numArr.filter((element)=>{
   return element%2===0;
})
console.log(evenArr) //[ 2, 4, 6, 8 ]

Reduce

Reduce iterate on the array and return only a single value on the basis of the function logic written, reduce is used to ans a very famous DS-ALGO question call sum of all elements of array, it can also be used to find ans of prefix sum array.

let arr = [10, 20, 30, 40];
previousValue = 0;
let sumOfArr = arr.reduce((previousValue, currentValue)=>{
   return previousValue + currentValue
})
console.log(sumOfArr); //100

Thank You for giving it a read🥳, I hope you liked it😁!

See you soon, Byee👋