Group By Property

JavaScript
Easy
Object

Asked in:

Airbnb
Facebook
Google
Salesforce
Flipkart
Description:

Write a function groupBy that takes an array of objects and a property name (as a string), and returns an object where the keys are the unique values of the specified property, and the values are arrays of objects that have that property value.

Sample Example:
// Example 1:
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 }
];

groupBy(users, 'age');
// Output:
// {
//   '25': [
//     { name: 'Alice', age: 25 },
//     { name: 'Charlie', age: 25 }
//   ],
//   '30': [
//     { name: 'Bob', age: 30 }
//   ]
// }

// Example 2:
const products = [
  { id: 1, category: 'Electronics' },
  { id: 2, category: 'Clothing' },
  { id: 3, category: 'Electronics' }
];

groupBy(products, 'category');
// Output:
// {
//   'Electronics': [
//     { id: 1, category: 'Electronics' },
//     { id: 3, category: 'Electronics' }
//   ],
//   'Clothing': [
//     { id: 2, category: 'Clothing' }
//   ]
// }

Now solving

Group By Property

Timer

15:00
Sign in
/**
 * Group By Property
 *
 * Description:
 * - Implement a function `groupBy` that groups an array of objects
 *   based on a given property.
 *
 * - The returned object should:
 *   • Use unique property values as keys
 *   • Map each key to an array of matching objects
 *
 * Constraints:
 * - `arr` can be empty
 * - Some objects may not contain the given key
 *
 * Debugging (Sandpack console): objects and arrays may look collapsed. Print the full result with:
 *   console.log(JSON.stringify(groupBy(users, 'age'), null, 2))
 *
 * Example:
 * const users = [
 *   { name: 'Alice', age: 25 },
 *   { name: 'Bob', age: 30 },
 *   { name: 'Charlie', age: 25 }
 * ];
 * groupBy(users, 'age');
 * // Output (object keys are strings in JS):
 * // {
 * //   '25': [
 * //     { name: 'Alice', age: 25 },
 * //     { name: 'Charlie', age: 25 }
 * //   ],
 * //   '30': [
 * //     { name: 'Bob', age: 30 }
 * //   ]
 * // }
 */
export function groupBy(arr, key) {
  // TODO: group objects by the given key

  return {} // placeholder
}

// Sample
console.log("InterviewPro Info — JavaScript practice");
const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 25 },
];
console.log('groupBy(users, "age") =>\n' + JSON.stringify(groupBy(users, "age"), null, 2));