Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Group array by equal values JavaScript
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 grouped 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 ] ]
Using reduce() with Map (Recommended)
We'll use Array.prototype.reduce() function to construct a new array, and we'll use a Map to keep track of the repeating entries in the array:
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));
[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]
Using Object for Counting
A simpler approach using a plain object to count occurrences:
const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night',
'noon', 'day', 'afternoon', 'day', 'night'];
const groupSimilarObject = arr => {
const counts = {};
// Count occurrences
arr.forEach(item => {
counts[item] = (counts[item] || 0) + 1;
});
// Convert to array format
return Object.entries(counts);
};
console.log(groupSimilarObject(array));
[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]
How It Works
The first method uses reduce() with a Map to maintain insertion order and track array indices. The accumulator object contains both the result data array and a Map for quick lookups. When an element is encountered for the first time, it's added to both the data array and Map. For subsequent occurrences, only the count is incremented.
The second method first counts all occurrences using a plain object, then converts it to the required array format using Object.entries().
Conclusion
Both approaches effectively group array elements by value and count their occurrences. The reduce() method maintains insertion order and is more efficient for large arrays, while the object-based approach is simpler to understand.
