Reduce an array to groups in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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


The code for this will be −

const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow',
const combineDuplicate = (arr = []) => {
   let prev = null;
   const groups = arr.reduce((acc, value) => {
      if (prev === value) {
         acc[acc.length - 1] += value;
      } else {
         prev = value
      return acc;
   }, [])
   return groups;


And the output in the console will be −

[ 'blueblue', 'green', 'blue', 'yellowyellow', 'green' ]
Published on 20-Nov-2020 18:06:30