Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reduce an array to groups in JavaScript
Suppose, we have an array of strings that contains some duplicate entries like this −
const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow', 'green'];
We are required to write a JavaScript function that takes in one such array. The function should merge all the duplicate entries with one another.
Therefore, the output for the above input should look like this −
const output = ['blueblue', 'green', 'blue', 'yellowyellow', 'green'];
Example
The code for this will be −
const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow',
'green'];
const combineDuplicate = (arr = []) => {
let prev = null;
const groups = arr.reduce((acc, value) => {
if (prev === value) {
acc[acc.length - 1] += value;
} else {
prev = value
acc.push(value)
}
return acc;
}, [])
return groups;
};
console.log(combineDuplicate(arr));
Output
And the output in the console will be −
[ 'blueblue', 'green', 'blue', 'yellowyellow', 'green' ]
Advertisements