
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}.
- The array contains elements: [1, 2, 2, 3, 1, 4, 2].
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}.
- The array contains elements: ["apple", "banana", "apple", "orange", "banana", "apple"].
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
Editorial
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. |
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