
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
Compress Array to Group Consecutive Elements in JavaScript
We are given a string that contains some repeating words separated by dash (-) like this −
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
Now our job is to write a function that returns an array of objects, where each object contains two properties value and count, value is the word in the string (Monday, Tuesday, Sunday) and count is their consecutive appearance count.
Like for the above string, this array would look something like this −
const arr = [{ val: 'monday', count: 1 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 2 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 3 }]
Because monday appears once, then sunday once, tuesday twice, sunday twice and lastly monday thrice.
We will split the array and then use Array.prototype.reduce() method to recursively return the desired array like this −
Here’s the complete code −
Example
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday'; const str2 = 'friday-friday-sunday-tuesday-sunday-sunday-monday-thursdaymonday'; const compressString = (str) => { return str.split('-').reduce((acc, val) => { const { length: l } = acc; if(acc[l-1]?.val === val){ acc[l-1].count++; return acc; }else{ return acc.concat({ val, count: 1 }); } }, []); } console.log(compressString(str)); console.log(compressString(str2));
Output
The output in the console for the above code will be −
[ { val: 'monday', count: 1 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 2 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 3 } ] [ { val: 'friday', count: 2 }, { val: 'sunday', count: 1 }, { val: 'tuesday', count: 1 }, { val: 'sunday', count: 2 }, { val: 'monday', count: 1 }, { val: 'thursday', count: 1 }, { val: 'monday', count: 1 } ]