Compress array to group consecutive elements 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 }
]
Updated on: 2020-08-20T06:22:33+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements