
Problem
Solution
Submissions
Group Array Elements
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to group array elements based on a specific criterion. The function should take an array of objects and a key, then group the objects by the values of that key. Return an object where each key represents a unique value from the specified property, and the value is an array of objects that have that property value.
Example 1
- Input: arr = [{name: "Alice", age: 25}, {name: "Bob", age: 25}, {name: "Charlie", age: 30}], key = "age"
- Output: {25: [{name: "Alice", age: 25}, {name: "Bob", age: 25}], 30: [{name: "Charlie", age: 30}]}
- Explanation:
- Initialize an empty result object to store grouped elements.
- Process first object {name: "Alice", age: 25} - create group for age 25.
- Process second object {name: "Bob", age: 25} - add to existing age 25 group.
- Process third object {name: "Charlie", age: 30} - create new group for age 30.
- Return the grouped object with two groups: age 25 and age 30.
- Initialize an empty result object to store grouped elements.
Example 2
- Input: arr = [{type: "fruit", name: "apple"}, {type: "vegetable", name: "carrot"}, {type: "fruit", name: "banana"}], key = "type"
- Output: {fruit: [{type: "fruit", name: "apple"}, {type: "fruit", name: "banana"}], vegetable: [{type: "vegetable", name: "carrot"}]}
- Explanation:
- Start with an empty result object. Group apple under "fruit" category.
- Group carrot under "vegetable" category.
- Add banana to existing "fruit" group.
- Return object with two groups: fruit and vegetable.
- Start with an empty result object. Group apple under "fruit" category.
Constraints
- 1 ≤ arr.length ≤ 1000
- Each object in the array contains the specified key
- The key value can be string, number, or boolean
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(n) for storing the grouped result
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 result object to store the grouped elements
- Iterate through each element in the input array
- For each element, extract the value of the specified key
- Check if this key value already exists in the result object
- If the key exists, push the current element to the existing array
- If the key doesn't exist, create a new array with the current element
- Return the final grouped object