To count how many times a specific value appears in a JavaScript array, validate that the input is an Array (Array.isArray(items)), scan elements using Object.is(item, targetValue) (or strict equality when appropriate) inside a try / catch block—handling NaN and +0 vs. -0 accurately where === differs from Object.is—and use a Map when counting frequencies across multiple values simultaneously so dynamic keys never collide with Object.prototype properties.
1. Counting Occurrences of a Target Value Safely with Object.is()
Validate Array.isArray(items) and iterate through the array inside try / catch, using Object.is(element, targetValue) so NaN values are counted reliably:
// Count how many times targetValue appears in a JavaScript array
function countValueOccurrences(items, targetValue, { useStrictEquality = false } = {}) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an Array instance.");
}
if (typeof useStrictEquality !== "boolean") {
throw new TypeError("Expected useStrictEquality to be a boolean.");
}
try {
let count = 0;
for (let i = 0; i < items.length; i += 1) {
const current = items[i];
const isMatch = useStrictEquality
? current === targetValue
: Object.is(current, targetValue);
if (isMatch) {
count += 1;
}
}
return count;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed counting value occurrences in array: ${message}`);
}
}
// Example usage:
// try {
// console.log(countValueOccurrences(["a", "b", "a", "c", "a"], "a")); // 3
// console.log(countValueOccurrences([1, NaN, 2, NaN], NaN)); // 2
// console.log(countValueOccurrences([1, NaN, 2, NaN], NaN, { useStrictEquality: true })); // 0
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Use
Object.is()forNaNand sign-sensitive checks:NaN === NaNevaluates tofalsein JavaScript, whereasObject.is(NaN, NaN)evaluates totrue. - Remember object/array matches are by reference: Two distinct object literals
{ id: 1 }and{ id: 1 }are not the same reference (Object.is(objA, objB)isfalse).
2. Counting All Array Frequencies at Once with a Map
When you need occurrence counts for all values (or a set of candidate values) in an array, use a Map to accumulate counts safely without Object.prototype key collisions:
// Build a Map of frequency counts for every element in an array
function countAllArrayFrequencies(items) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an Array instance.");
}
try {
const frequencyMap = new Map();
for (const item of items) {
const previousCount = frequencyMap.get(item) ?? 0;
frequencyMap.set(item, previousCount + 1);
}
return frequencyMap;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed building array frequency Map: ${message}`);
}
}
// Example usage:
// try {
// const roles = ["editor", "viewer", "editor", "admin", "viewer", "editor"];
// const freqMap = countAllArrayFrequencies(roles);
// console.log("Editor count:", freqMap.get("editor")); // 3
// console.log("Viewer count:", freqMap.get("viewer")); // 2
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Use
Maprather than a plain{}object:Mapsupports keys of any type (NaN, objects, numbers, symbols) and avoids collisions withconstructor,toString, orhasOwnProperty. - Avoid
.filter(x => x === val).lengthon huge hot arrays when avoidable: A single loop avoids allocating an intermediate filtered array on every lookup.
3. Sparse Arrays, Reference Equality, and Type Pitfalls
Keep these array-counting edge cases in mind in production code:
- Sparse arrays (
new Array(3)or[1, , 3]) have empty slots: Afor...ofloop visitsundefinedat empty slots, whereas a standard index loopfor (let i = 0; i < arr.length; i += 1)readsarr[i]asundefined—know how you want holes vs. explicitundefinedtreated. - Primitive vs. boxed wrapper objects (
"abc"vs.new String("abc")): Prefer primitive values and strict validation (typeof/Array.isArray) rather than boxed primitives. - Always validate
Array.isArray(items)before iterating: Passingnull,undefined, or a non-array object otherwise causes runtime failures or silent miscounts.
