Let’s say, we have an array of string / number literals that contains some duplicate values like this −
const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night'];
We are required to write a function groupSimilar() that takes in this array and returns a new array where all the repeating entries are group together in a subarray as the first element and their total count in the original array as the second element.
So, for this example, the output should be −
[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]
Let’s write the code for this function. We will use the Array.prototype.map() function to construct a new, required, array, and we will use a Map to keep track of the repeating entries in the array −
Example
const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night']; const groupSimilar = arr => { return arr.reduce((acc, val) => { const { data, map } = acc; const ind = map.get(val); if(map.has(val)){ data[ind][1]++; } else { map.set(val, data.push([val, 1])-1); } return { data, map }; }, { data: [], map: new Map() }).data; }; console.log(groupSimilar(array));
Output
The output in the console will be −
[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]