Medium

Count the Occurrences of Elements in an Array

Description

You are required to write a JavaScript function that takes an array of elements as input and returns an object.

The object should contain each unique element from the array as a key and its occurrence count as the value.

This task is commonly used in data processing, such as:

  • Analyzing frequency distributions (e.g., finding the most common words in a text).
  • Counting occurrences of user interactions (e.g., button clicks, page visits).
  • Aggregating data for reporting or analytics.

Requirements

Input: An array of elements (e.g., numbers, strings, or mixed types).

Output: An object where each unique element in the array is a key. The corresponding value represents the count of that element in the array.

Considerations:

  • Handle different data types (numbers, strings, booleans, etc.).
  • Ensure the function can process empty arrays correctly, returning an empty object.
  • Be mindful of case sensitivity for string elements (e.g., "A" vs "a").

Example Usage

countOccurrences(["apple", "banana", "apple", "orange", "banana", "apple"]);
// Expected output: { apple: 3, banana: 2, orange: 1 }
countOccurrences([1, 2, 2, 3, 1, 1, 4]);
// Expected output: { 1: 3, 2: 2, 3: 1, 4: 1 }
countOccurrences([]);
// Expected output: {}

window code 2Test Cases

Input:

[
  1,
  2,
  2,
  3,
  3,
  3,
  4
]

Expected Output:

"{\"1\":1,\"2\":2,\"3\":3,\"4\":1}"