Shohail ahmed
29 Jul 2021
•
2 min read
“Every developer who specializes in any programming language will tell you there’s a powerful tool the language provides that they rarely use and wish they knew more about. For me, it’s
Array.prototype.reduce
.”What is Reduce?
The reduce()
method is used to apply a function to each element in the array to reduce the array to a single value.
The syntax looks like this
const reduced=arr.reduce((acc,val,ind,srcArr)
reduce() takes a callback with 4 arguments
Accumaltor(acc)
: the accumulator accumulates all of the callbacks returned values.
currentValue(val)
: The current element being processed in the array.
index(idx)
: The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.
sourceArray(srcArr)
: The array on whichreduce() is being called.
You can think of reduce()
as a for loop, that is specifically for using the values of an array to create something new. Consider the following code:
const arr=[1,2,3,4,5]
const reduced=arr.reduce((acc,val)=>acc+val); ///15
//Array has been reduced to a single value`
Passing initial value to reduce
we can pass initial value to reduce for Example:
`const arr=[1,2,3,4,5]
const reduced=arr.reduce((acc,val)=>acc+val,100); ///115
First value in accumulator is 100 Pretty cool huh? With just one line of code we can take the number 100 and add it to the sum of an entire array!
Reduce can return objects
Methods like forEach
and map
were created to avoid side effects, and reduce is no exception. In this case, however, reduce
can return an Object
other than an Array
let’s take an example for Counting Array Elements and returning it in Object
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {} );
// counted Names is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Note that the {}
, which is the last argument to reduce
, is starting/default object to be returned. If there were no items in the array, {}
would be returned. Also appreciate that an array method returns an object literal and not a modified array!
Awesome!
let’s see one more example where we group an array of people’s info with age
Reduce makes our life easier It’s crazy that I’ve not used reduce
more.
Learn More: MDN : Array.prototype.reduce()
Thanks!
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!