

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' ]
- Related Questions & Answers
- Splitting an array into groups in JavaScript
- Reduce array in JavaScript
- Reduce an array to the sum of every nth element - JavaScript
- Sorting Array with JavaScript reduce function - JavaScript
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- Comparing forEach() and reduce() for summing an array of numbers in JavaScript.
- JavaScript reduce sum array with undefined values
- How to reduce an array while merging one of its field as well in JavaScript
- Separating data type from array into groups in JavaScript
- Python program to reverse an array in groups of given size?
- Java program to reverse an array in groups of given size
- Convert 2D array to object using map or reduce in JavaScript
- How to reduce arrays in JavaScript?
- How to convert array into array of objects using map() and reduce() in JavaScript
- Finding the product of array elements with reduce() in JavaScript
Advertisements