 # Learn Javascript Reduce method with 10 examples

May 04, 2020

The reduce method applies a function to every item of an array and accumulates the result iteratively from a starting point then returns a single value/object.

This starting value can be specified or if not reduce will use the first item in the array.

Most of these examples might not be the idea solution for the problem, but the idea is to illustrate how we can use reduce to solve them.

## Summation and Multiplication:

``````[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);

// Without initial value
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );

// For clarity the above code is the same as
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );

// Multiplication
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);``````

In this example you can leave the initial value out, as it will grab the first item in the array, but you can also give it to have an offset or a bias pretty useful for that.

## Find the maximum in an array:

``[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);``

Here in each iteration we return the max between the accumulator and the current item and in the end we have the max of the entire array.

Don't use this if you actually want to find the max in an array, you could use:

``````Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
``````

## Concatenating uneven arrays

``````let data = [
["The","red", "horse"],
["Plane","over","the","ocean"],
["Chocolate","ice","cream","is","awesome"],
["this","is","a","long","sentence"]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`\${a} \${i}`))

// Result
['The red horse',
'Plane over the ocean',
'Chocolate ice cream is awesome',
'this is a long sentence']
``````

Pretty simple, here we also use map to go through each item in the array and we do a reduce with all the arrays.

## Removing duplicates in an array:

``````let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
return noDupes
}, [])
``````

We check if the current value has index on the accumulator array if not is going to return -1 hence is not in the array and we can add it.
You can do this much better with a javascript set, since by default it stores only unique values, but either way i think it's a neat algorithm to think about.

## Validating parenthesis

``````[..."(())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);

//Long way with for loop
status=0
for i in string:
if(i=="("):
status=status+1
elif(i==")"):
status=status-1
if(status<0):
return False
``````

This is a cool one that I adapted from a coding challenge that I did a while ago.
In the long way we can end the loop sooner, by checking if status is less than 0 in any point.
Here the condition is, if status is 0, the parenthesis are correct otherwise there is an imbalance.

## Group by property

``````let obj = [
{name: 'Alice', job: 'Data Analyst', country: 'AU'},
{name: 'Bob', job: 'Pilot', country: 'US'},
{name: 'Lewis', job: 'Pilot', country: 'US'},
{name: 'Karen', job: 'Software Eng', country: 'CA'},
{name: 'Jona', job: 'Painter', country: 'CA'},
{name: 'Jeremy', job: 'Artist', country: 'SP'},
]
let ppl = obj.reduce((group, curP) => {
let newkey = curP['country']
if(!group[newkey]){
group[newkey]=[]
}
group[newkey].push(curP)
return group
}, [])
``````

Here we group the first array of objects by the country key, in each iteration, we check if the key exist if not we create an array, then we add the current person to that and we return the group array.

You can make a function with this to group the objects with an specified key.

## Flattened an array of arrays

``````let flattened = [[3, 4, 5], [2, 5, 3], [4, 5, 6]].reduce(
(singleArr, nextArray) => singleArr.concat(nextArray), [])
// results is [3, 4, 5, 2, 5, 3, 4, 5, 6]
``````

This is only 1 level deep but it you can adapt this with a recursive function, but i'm not that fan of making recursive things on javascript 😂
An intended way of doing this is just to use the .flat method, it will do the same

``````[ [3, 4, 5],
[2, 5, 3],
[4, 5, 6]
].flat();
``````

## Power only positive numbers

``````[-3, 4, 7, 2, 4].reduce((acc, cur) => {
if (cur> 0) {
let R = cur**2;
acc.push(R);
}
return acc;
}, []);

// Result
[16, 49, 4, 144]
``````

This one is like doing a map and a filter at the same time, we filter the negative numbers and we rise the positive.

## Reverse a string

``````const reverseStr = str=>[...str].reduce((a,v)=>v+a)
``````

This will work with any object not only with strings, also note that with this syntax we have the reduce in a function so we can call reverseStr("Hola") and it will give aloH 😂

## Binary to decimal

``````const bin2dec = str=>[...String(str)].reduce((acc,cur)=>+cur+acc*2,0)

const bin2dec = (str) => {
return [...String(str)].reduce((acc,cur)=>{
return +cur+acc*2
},0)
}
``````

#### Ramiro

Hey hi! My name is Ramiro, this is my blog about artificial intelligence, coding and things that are in my head. Follow me on twitter @ramgendeploy so we can chat!

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.