Write a function `countOccurrences(arr)` that returns an object with each element as key and its count as value.
Problem Statement
Write a function `countOccurrences(arr)` that returns an object with each element as key and its count as value.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Array.reduce() reduces an array to a single value (which can be an object).
š” Hint 2:
Use an object as the accumulator and increment counts.
š” Hint 3:
return arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {});
ā
Solution:
```javascript
function countOccurrences(arr) {
return arr.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc; }, {});
}
```