- Returns single value.
- Doesn't mutate original array.
- Doesn't execute the function for empty array elements.
- Syntax:
array.reduce(function(previousValue, currentValue, currentIndex, arr), initialValue);
const reduceArr = [1,2,3,4];
reduceArr.reduce((total, currentValue) => total+currentValue);
> 10
reduceArr //Doesn't mutate original array
> [1, 2, 3, 4]
reduceArr.reduce((total, currentValue) => total+currentValue, 10); // 10 is Initial value
> 20
previousValue:
value resulting from the previous call to callBackFn. On first call, initialValue
if specified otherwise array[0]
.
currentValue:
value of the current element.On the first call, the value of array[0] if initialValue
specified otherwise array[1]
.
currentIndex:
currentValue index. On first call it is 0 if initialValue
specified otherwise 1.
const array = [10, 20, 30, 40];
function reducer(previousValue, currentValue, index, array) {
const result = previousValue + currentValue;
console.log(`previous: ${previousValue}, current:${currentValue}, index: ${index}, array: ${array}`);
return result;
}
array.reduce(reducer);
> previous: 10, current: 20, index: 1, array: 10,20,30,40
> previous: 30, current: 30, index: 2, array: 10,20,30,40
> previous: 60, current: 40, index: 3, array: 10,20,30,40
> 100
Examples:
1.Flatten array using reduce.
[[1,2],[3,4],[4,5]].reduce((p,n) => p.concat(n));
> [1, 2, 3, 4, 4, 5]
2.Find instances of values in array.
['first', 'second', 'third', 'first', 'fourth', 'second'].reduce((list, name) => {
if(name in list) {
list[name]++;
} else {
list[name] = 1;
}
return list;
}, {});
> {first: 2, second: 2, third: 1, fourth: 1}
3.Group objects by property.
const obj = [
{name: 'Alex',age: 30},
{name: 'Max', age: 30},
{name: 'sony', age: 20},
{name: 'molly', age: 20}
];
function groupByProperty(array, prop) {
return array.reduce((list, current) => {
let key = current[prop];
if(!list[key]) {
list[key] = [];
}
list[key].push(current);
return list;
}, {})};
groupByProperty(obj, 'age');
> {
"20": [
{
"name": "sony",
"age": 20
},
{
"name": "molly",
"age": 20
}
],
"30": [
{
"name": "Alex",
"age": 30
},
{
"name": "Max",
"age": 30
}
]
}
4.Remove duplicate items.
['a', 'b', 'c', 'a', 'b','c'].reduce((previous, current) => {
if(previous.indexOf(current) === -1) {
previous.push(current);
}
return previous;
}, []);
> ['a', 'b', 'c']
5.Functional Composition.
const double = x => x+x;
const triple = x => 3 * x;
const pipe = (...functions) => input => functions.reduce((acc, fn, index) => {
console.log(`iteration: ${index}, accValue: ${acc}`);
return fn(acc)},input);
const multiply6 = pipe(double, triple);
multiply6(6);
> iteration: 0, accValue: 6
> iteration: 1, accValue: 12
> 36
You can follow me here: https://twitter.com/urstrulyvishwak
Top comments (4)
Just to clarify, you don't need
Array.prototype.reduce
for all that:Array.prototype.flat
instead:Array.prototype.group
instead (or a polyfill of it):Set
instead:The actual real world cases in which
Array.prototype.reduce
is useful are little. Mainly sums and products, other stuff can be achieved with clearer functions.Cheers!
Cool. My intention is how
reduce
works.Hi,
Can you please give me your email or any contact. I need a parttime writer who can write on JavaScript, React, Vue, Next.js and more.
Is the reduce() function using a recursion behind the scenes ?