Computer >> Computer tutorials >  >> Programming >> Javascript

Group matching element in array in JavaScript


Suppose, we have an array of alphabets that contains some repeating alphabets like this −

const arr = [
   'a','a','a','a','d','e','e','f','h','h','h','i','l','m','n',
   'r','s','s',' t','u','v','y','y'
];

We are required to write a JavaScript function that takes in one such array. The function should group all the identical aphabets into their unique subarray.

Therefore, for the above array, the output should look like −

const output = [
   ['a','a','a','a'], ['d'], ['e','e'], ['f'], ['h','h','h'],
   ['i'], ['l'], ['m'], ['n'], ['r'], ['s','s'], ['t'], ['u'],
   ['v'], ['y','y']
];

Example

The code for this will be −

const arr = [
   'a','a','a','a','d','e','e','f','h','h','h','i','l','m','n','r','s','s','
   t','u','v','y','y'
];
const bringAlong = (arr = []) => {
   const hash = {};
   return arr.reduce(function(res, e) {
      if(hash[e] === undefined)
         hash[e] = res.push([e]) − 1;
      else
         res[hash[e]].push(e);
      return res;
   }, []);
};
console.log(bringAlong(arr));

Output

And the output in the console will be −

[
   [ 'a', 'a', 'a', 'a' ],
   [ 'd' ],
   [ 'e', 'e' ],
   [ 'f' ],
   [ 'h', 'h', 'h' ],
   [ 'i' ],
   [ 'l' ],
   [ 'm' ],
   [ 'n' ],
   [ 'r' ],
   [ 's', 's' ],
   [ 't' ],
   [ 'u' ],
   [ 'v' ],
   [ 'y', 'y' ]
]