javascriptintermediate10 minutes

Build a Function to Group Objects by a Key

Create a JavaScript function that groups an array of objects by a specified key, returning an object where each key maps to an array of items sharing that key's value.

Challenge prompt

Write a function named 'groupBy' that takes two parameters: an array of objects, and a string that represents the key to group by. The function should return an object where each property is a unique value from the specified key in the objects, and the corresponding value is an array of all objects that have that key value. Example: groupBy([{age: 23, name: 'Alice'}, {age: 23, name: 'Bob'}, {age: 30, name: 'Charlie'}], 'age') should return: { 23: [{age: 23, name: 'Alice'}, {age: 23, name: 'Bob'}], 30: [{age: 30, name: 'Charlie'}] } Make sure your function works for any key and array size.

Guidance

  • Iterate through each object in the input array.
  • Check if the grouping key's value already exists in the result object.
  • If it does, push the current object into the appropriate array; otherwise, create a new array with the current object.

Hints

  • Use the array 'reduce' method to accumulate grouped results efficiently.
  • Remember that object properties can be accessed dynamically using bracket notation.
  • Check if the key exists by using 'hasOwnProperty' or a simple truthy check.

Starter code

function groupBy(array, key) {
  const result = {};
  // Your code here
  return result;
}

Expected output

{ 23: [ { age: 23, name: 'Alice' }, { age: 23, name: 'Bob' } ], 30: [ { age: 30, name: 'Charlie' } ] }

Core concepts

arraysobjectsiterationhigher-order functions

Challenge a Friend

Send this duel to someone else and see if they can solve it.