How to use Reduce Method In Javascript
In this approach, we will use the reduce method to create an object that tracks the count of each character. Then, we will loop through this object to identify and print characters that have a count greater than one.
Example: Using the reduce Method
function printDupsUsingReduce(str) {
// Using reduce to build the character count object
let charCount = str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
// Iterating over the charCount object to print duplicates
Object.keys(charCount).forEach(char => {
if (charCount[char] > 1) {
console.log(`${char}, count = ${charCount[char]}`);
}
});
}
let str = "w3wiki";
printDupsUsingReduce(str);
Output
g, count = 2 e, count = 4 k, count = 2 s, count = 2
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string.
Example:
Input: S = “w3wiki”
Output:
e, count = 4
g, count = 2
k, count = 2
s, count = 2
Table of Content
- Using For Loop in JavaScript
- Using Sorting in JavaScript
- Using Hashing in JavaScript
- Using Set()
- Using Reduce Method in JavaScript