How do you count how many times a specific value appears in a JavaScript array? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you count how many times a specific value appears in a JavaScript array?

message-square
0

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() for NaN and sign-sensitive checks: NaN === NaN evaluates to false in JavaScript, whereas Object.is(NaN, NaN) evaluates to true.
  • 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) is false).

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 Map rather than a plain {} object: Map supports keys of any type (NaN, objects, numbers, symbols) and avoids collisions with constructor, toString, or hasOwnProperty.
  • Avoid .filter(x => x === val).length on 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: A for...of loop visits undefined at empty slots, whereas a standard index loop for (let i = 0; i < arr.length; i += 1) reads arr[i] as undefined—know how you want holes vs. explicit undefined treated.
  • 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: Passing null, undefined, or a non-array object otherwise causes runtime failures or silent miscounts.