🟨 JavaScript
Medium
🕐 15 min

Group Objects by Key

Goal: to implement a universal function for data grouping, which is often used in data processing and analytics.

💡 Solution Hint

The main idea is to iterate over the array and place elements into an object, using the key’s value for grouping.

  1. Initialization: Create an empty object to store the result (result = {}).
  2. Iteration: Loop through each object (item) in the source array using a loop like forEach.
  3. Get Key: For each object, get the value of the key specified in the key argument (groupKey = item[key]).
  4. Grouping:
    • Check if a property with the name groupKey exists in result (if (!result[groupKey])).
    • If it doesn’t, create it and assign it an empty array: result[groupKey] = [].
    • Add the current item to the array corresponding to that key: result[groupKey].push(item).
  5. Completion: After iterating through all elements, return result.

This approach can be elegantly implemented using the Array.prototype.reduce method.

👀 Solution
const groupBy = (arr, key) => {
  // Use reduce to transform the array into an object.
  // accumulator (acc) is the object we will build.
  // current (obj) is the current element of the array.
  return arr.reduce((acc, obj) => {
    // Get the key value for the current object.
    const groupKey = obj[key];
 
    // If the accumulator doesn't have an array for this key yet, create one.
    if (!acc[groupKey]) {
      acc[groupKey] = [];
    }
 
    // Add the current object to the array corresponding to its key.
    acc[groupKey].push(obj);
 
    // Return the updated accumulator for the next iteration.
    return acc;
  }, {}); // The initial value for the accumulator is an empty object.
};

Solution Analysis:

  • Time Complexity: O(n), where n is the number of elements in the array. We iterate through the array once.
  • Space Complexity: O(n), because in the worst case (if all keys are unique), we will create a new object containing all the elements of the original array.

Task Description

You need to implement a function groupBy that takes an array of objects arr and a string key. The function should group all objects from the array by the value of their key property and return an object where the keys are the property values, and the values are arrays of objects with that key.

This method is incredibly useful for organizing data, for example, for grouping a list of users by city or products by category.

Examples

const data = [
  { city: 'Moscow', temp: 15 },
  { city: 'London', temp: 12 },
  { city: 'Moscow', temp: 18 },
  { city: 'Paris', temp: 20 },
  { city: 'London', temp: 14 }
];
 
groupBy(data, 'city');
/*
{
  "Moscow": [
    { "city": "Moscow", "temp": 15 },
    { "city": "Moscow", "temp": 18 }
  ],
  "London": [
    { "city": "London", "temp": 12 },
    { "city": "London", "temp": 14 }
  ],
  "Paris": [
    { "city": "Paris", "temp": 20 }
  ]
}
*/

Requirements

  • The function must be named groupBy.
  • If the input array is empty, the function should return an empty object.
  • If an object is missing the grouping key, it should be grouped under the key undefined.

🧑‍💻 It's not a bug! It's a feature!

The code editor is intentionally hidden on mobile.

Believe me, it's for the best: I am protecting you from the temptation to code in less-than-ideal conditions. A small screen and a virtual keyboard are not the best tools for a programmer.

📖 Now: Study the task, think through the solution. Act like a strategist.

💻 Later: Sit down at your computer, open the site, and implement all your ideas comfortably. Act like a code-jedi!