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' ]

Updated on: 20-Nov-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements