A reduce function is a reliable tool for dynamically tallying elements in arrays. Here, an object count gets populated with keys (unique array elements) and values (their occurrence count):
In the realm of data processing and visualization, knowing how to count the frequency of array elements effectively is a game-changer. This section explores different variations, their practicality, and associated gotchas.
Using Map for cleaner, modern counting
With a Map object, you can achieve clean code with even cleaner access mechanisms:
const fruits = ['apple', 'banana', 'apple'];
const count = newMap(); // A Map is not the territory. Or is it? 🤔fruits.forEach(fruit => count.set(fruit, (count.get(fruit) || 0) + 1));
for (const [key, value] of count.entries()) {
console.log(`${key}: ${value}`); // Here's where we spill the beans...or fruits}
Immutably count frequencies with reduce and spread
To keep the side effects at bay, clone your array with spread operator:
Grouping identical elements together with sort before counting, all for easier logic and possible time complexity reduction:
const sortedFruits = ['apple', 'apple', 'banana'].sort();
let previousFruit, frequency = 1; // Ah, our first fruit to count.for (let i = 1; i <= sortedFruits.length; i++) {
if (sortedFruits[i] === previousFruit) {
frequency++; // Same fruit? Increase the count. } else {
if (previousFruit !== undefined) {
console.log(`${previousFruit}: ${frequency}`); // Hello, we've got a count for you! }
previousFruit = sortedFruits[i];
frequency = 1; // Reset count for the new fruit. }
}
Let libraries lend a helping hand
With lodash or underscore we're in expressive, low boilerplate territory. Here, we are using lodash's _.countBy:
const fruits = ['apple', 'banana', 'apple'];
const count = _.countBy(fruits); // This function never goes bananas... it just counts them!console.log(count); // { apple: 2, banana: 1 }
Tackling the complex cases
When your arrays contain more than just primitive values and start venturing into complex territories (objects or arrays), you need to up your frequency counter game:
Good old JSON for complex keys
Use JSON.stringify() to convert complex elements to a string: