javascriptintermediate10 minutes
Create a Function to Group and Count Array Elements by Key
Build a JavaScript function that groups objects in an array by a specific key and returns the count of each group.
Challenge prompt
Write a function named 'groupByCount' that takes two parameters: an array of objects and a string key. The function should return an object where the keys are the unique values from the specified key in the objects, and the values are the count of how many times each unique value appears in the array. For example, given an array of objects representing people and the key 'age', the function should group people by their age and count how many have the same age.
Guidance
- • Iterate over the array and use an object to keep track of counts by the specified key.
- • Check if the key exists in the object; if not, initialize it to zero before incrementing.
- • Return the final object with grouped counts once all array elements have been processed.
Hints
- • Consider using the array's forEach or reduce methods for iteration.
- • Remember to handle cases where some objects might not contain the specified key.
- • You may use short-circuit evaluation to simplify incrementing counts.
Starter code
function groupByCount(arr, key) {
// Your code here
}Expected output
{ '25': 3, '30': 2, '40': 1 }
Core concepts
object manipulationarray iterationcounting/grouping
Challenge a Friend
Send this duel to someone else and see if they can solve it.