Welcome back, developers! This is the second part of understanding how to use reduce method in JavaScript. Click here to check part 1 of the reduce method. Needless to say, this article is more of the same. We will go through various ways to see how JavaScript reduce method is implemented. So, let’s start. 

When to Apply JavaScript Reduce Method? 

JavaScript Reduce method is applicable in tons of places. Let’s take a look at a few of such examples

  • Concatenating Nested List
  • Removing Duplicate Using Reduce Method 
  • Reversing a String Using Reduce Method 

Concatenating Nested List

				
					let listOfLists = [
    ["My", "name", "is", "Daniyal"], 
    ["Welcome", "to", "Programatically"], 
    ["This", "is", "a", "developers", "community"], 
    ["Here", "we", "help", "each", "other", "out"], 
]; 
const singleList = listOfLists.map((item) => 
  item.reduce((a, i) => `${a} ${i}`) 
); 
console.log(singleList); 
 
// OUTPUT 
[ 
  'My name is Daniyal', 
  'Welcome to Programatically', 
  'This is a developers community', 
  'Here we help each other out' 
] 
				
			

In this one, you can see the initial nested list and the final single list. Using reduce method coupled with the map method in order to return the output in list format. Lambda function really takes makes the task even easier. 

Removing Duplicate Using Reduce Method

				
					listOfNumbers = [2, 4, 6, 8, 8, 10, 2, 4, 4, 6, 18, 20];
  
var newList = listOfNumbers.reduce((noDuplicates, item) => { 
  if (noDuplicates.indexOf(item) === -1) { 
    noDuplicates.push(item); 
  } 
  return noDuplicates; 
}, []); 
console.log(newList); 
				
			

In here you can see we are initializing noDuplicates’ variable as an empty list. Then checking individual elements from the listOfNumbers that whether we’ve already pushed it in noDuplicates’ list. If not then we do push them, else we do nothing. In the end, noDuplicates’ is returned and stored in newList’ variable. This is how we remove duplicate values from a list using reduce method in JavaScript. Check the code in action shown below: 

JavaScript Reduce Method
JavaScript Reduce Method

Reversing a String Using Reduce Method in JavaScript

				
					const reverseIt = str=>[...str].reduce((a,b)=>b+a)
console.log(reverseIt("Programatically")); 
  
//OUTPUT: yllacitamargorP 
				
			

This is basically a function which you can call like so: reverseIt(“STRING”) 

The string value that you will pass in the reverseIt()’ method is being separated individually in a list using JavaScript Spread method. Then using the reduce method, each alphabet is being concatenated in reverse order. Its then printed on the console log.

That’s a wrap! 
I hope you guys found this article helpful. Now you should have a better understanding of how to use reduce method in JavaScript. For more articles like this, leave your reviews in the comment section below.  

Have a great one!