When it comes to code in JavaScript, developers found reduce function as one of the toughest concepts to crack. According to Wikipedia, Reduce has multiple names viz. Accumulate, Fold, Compress and Aggregate. These names clearly indicate the meaning & working of reduce function. The idea behind this is to break down a structure into a single value. Hence, Reduce can be defined as a function which converts a list into any data type.
For example, you can reduce an array [5,4,3,2,1] into the value 15 by just adding them.
Reduce function keeps developers away from using loop in order to fold a list into a single value.
In this blog, you will learn ways to implement well-known functions using reduce as already done by developers in
top software development company.
I have listed out 10 JavaScript utility functions recreated using reduce function. So, check out below these functions:-
Parameters used
array (to transform list of items), transform Function (is a function used to run on each element)
Working
By using the given transformFunction, each element in the given array get transformed and returns new array of items.
How to implement?
const map = (transformFunction, array1) =>
array1.reduce((newArray1, xyz) =>
{
newArray1.push(transformFunction(xyz));
return newArray1;
},
[]
);
Use case:
const double = (x) => x * 2;
const reverseString = (string) =>
string
.split('')
.reverse()
.join('');
map(double, [200, 300, 400]);
Output: [400, 600, 800]
map(reverseString, ['Hello Alka', 'I love cooking']);
// ['alkA olleH', ‘gnikooc evol I']