Tutorialspoint
Problem
Solution
Submissions

Count Occurrences in Array

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a JavaScript program to count the occurrences of each element in an array and return the result as an object. Given an array of elements, create an object where each unique element from the array becomes a key, and its corresponding value represents how many times that element appears in the array.

Example 1
  • Input: arr = [1, 2, 2, 3, 1, 4, 2]
  • Output: {1: 2, 2: 3, 3: 1, 4: 1}
  • Explanation:
    • The array contains elements: [1, 2, 2, 3, 1, 4, 2].
    • Element 1 appears at positions 0 and 4, so count is 2.
    • Element 2 appears at positions 1, 2, and 6, so count is 3.
    • Element 3 appears at position 3, so count is 1.
    • Element 4 appears at position 5, so count is 1.
    • Final count object: {1: 2, 2: 3, 3: 1, 4: 1}.
Example 2
  • Input: arr = ["apple", "banana", "apple", "orange", "banana", "apple"]
  • Output: {"apple": 3, "banana": 2, "orange": 1}
  • Explanation:
    • The array contains elements: ["apple", "banana", "apple", "orange", "banana", "apple"].
    • "apple" appears at positions 0, 2, and 5, so count is 3.
    • "banana" appears at positions 1 and 4, so count is 2.
    • "orange" appears at position 3, so count is 1.
    • Final count object: {"apple": 3, "banana": 2, "orange": 1}.
Constraints
  • 1 ≤ arr.length ≤ 1000
  • Array elements can be numbers, strings, or other primitive types
  • Time Complexity: O(n) where n is the length of array
  • Space Complexity: O(k) where k is the number of unique elements
ArraysNumberCapgeminiPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create an empty object to store the count of each element
  • Iterate through each element in the input array
  • For each element, check if it already exists as a key in the count object
  • If it exists, increment its count by 1
  • If it doesn't exist, initialize its count to 1
  • Return the final count object containing all occurrences

Steps to solve by this approach:

 Step 1: Initialize an empty object called 'count' to store element frequencies.
 Step 2: Start iterating through each element of the input array using a for loop.
 Step 3: For each element, store it in a variable for easier reference.
 Step 4: Check if the current element already exists as a key in the count object.
 Step 5: If the element exists, increment its count value by 1.
 Step 6: If the element doesn't exist, initialize it with a count of 1.
 Step 7: Continue this process for all elements and return the final count object.

Submitted Code :