Explain Codes LogoExplain Codes Logo

How to count certain elements in an array?

javascript
performance
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Sep 22, 2024
TLDR

Unravel the magic of counting elements in an array by filtering the matches and applying some length algebra:

const count = (arr, val) => arr.filter(x => x === val).length; console.log(count([1, 2, 2, 3], 2)); // Output: 2

This charming line of code creates a sizzling new array, holding on to just the occurrences of val and promptly reports back its size.

Exploring alternative array traversal techniques

While our trusty one-liner above can do the job just fine for a variety of cases, it's worth venturing into the realm of performance considerations, where handling colossal arrays without mutating or producing ancillary arrays becomes necessary.

The memory-efficient reduce

Consider using the reduce method when you're eager to keep your memory footprint admirable:

const countReduce = (arr, val) => arr.reduce((acc, cur) => (cur === val ? acc + 1 : acc), 0); console.log(countReduce([1, 2, 2, 3], 2)); // Output: 2 because 2 decided to show up twice at the party!

reduce compiles a single result without spawning new arrays, effectively making your program's memory consumption more frugal. This technique gains significance in high-performance scenarios or mammoth datasets!

Introducing forEach for readability

Fall in love with the sleek and modern forEach:

let count = 0; [1, 2, 2, 3].forEach(item => item === 2 && count++); console.log(count); // Output: 2. Forever together: Count and 2

This brief and expressive code retains the spirit of higher-order functions whilst potentially cutting down on memory use as opposed to filter.

Embracing the Multiset for multi-value counts

Here's where a multiset - an object that maintains counts - comes in handy when you're in the mood for counting multiple values:

const counts = array.reduce((acc, val) => { acc[val] = (acc[val] || 0) + 1; return acc; }, {}); console.log(counts['2']); // Output: Another version of Hide & Seek: Finding 2 in the array

This tactic avoids multiple traversals through the array for different values, proving itself a more efficient approach as the distinct values in the array increase.

Performance optimization considerations

Though the functional paradigms strike as stylish, they might not always top the speed charts. Do remember to subject your functions to tests on platforms like jsperf.com for insightful performance benchmarks. Size does matter - especially when working with substantial arrays.

Prototype Extension with given thought

Prototyping can be alluring with its elegance and shortcut potential. But remember to proceed with caution. Keep an eye out for name conflicts and code behavior hijacking.

Array.prototype.countElement = function (val) { return this.filter(x => x === val).length; }; const array = [1, 2, 2, 3]; console.log(array.countElement(2)); // Output: 2. Array's got a new superpower: countElement!

When extending prototypes ensure your function names are unique to prevent clashes with native or third-party array methods.

Strict Equality — Not Just a suggestion

Always extol the virtues of === for strict equality comparison to evade rude shocks from unexpected type coercion:

console.log(count([1, '2', 2, 3], 2)); // Output using `==`: 3 console.log(count([1, '2', 2, 3], 2)); // Output using `===`: 2

By enforcing that the values being compared share both the same value and type, triple equals (===) yields precise comparisons, making your code's results consistent across different environments.