javascriptintermediate10 minutes

Build a Function to Group Objects by Property in JavaScript

Create a function that takes an array of objects and groups them by a specified property, returning an object where keys are property values and values are arrays of matching objects.

Challenge prompt

Write a JavaScript function named 'groupBy' that accepts two parameters: an array of objects and a string representing a property key. The function should return an object where each key is a unique value of the specified property from the array, and each corresponding value is an array containing all objects from the original array that share that property value. If the property does not exist in some objects, group those objects under the key 'undefined'.

Guidance

  • Iterate through the array and extract the property value for each object.
  • Use an object to aggregate arrays grouped by the property value.
  • Handle cases where the property is missing or undefined by grouping under 'undefined'.

Hints

  • Consider using the array method 'reduce' to accumulate results.
  • Use bracket notation to dynamically assign keys to the result object.
  • Make sure to initialize arrays for new keys before pushing objects.

Starter code

function groupBy(array, key) {
  // Your code here
}

Expected output

groupBy([{category: 'fruit', name: 'apple'}, {category: 'vegetable', name: 'carrot'}, {category: 'fruit', name: 'banana'}, {name: 'unknown'}], 'category') // Returns: // { // fruit: [ {category: 'fruit', name: 'apple'}, {category: 'fruit', name: 'banana'} ], // vegetable: [ {category: 'vegetable', name: 'carrot'} ], // undefined: [ {name: 'unknown'} ] // }

Core concepts

array methodsobject manipulationhigher-order functions

Challenge a Friend

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