Coding Challenge - #16: Group Array Elements

Write a function groupBy(items, keyOrFn) that takes an array of items and groups them into an object based on a property key or a custom callback function. For example, groupBy(['apple', 'banana', 'avocado'], word => word[0]) should return { a: ['apple', 'avocado'], b: ['banana'] }.

function groupBy(items, keyOrFn) {
  // your code here
}

Rules:

  • Support both a string key and a callback function as the second argument.
  • Return a plain JavaScript object mapping group keys to arrays of matching items.
  • Do not use external libraries or Object.groupBy.

Post your solution as a reply. Answer goes up in about a day.

1 Like

Wow. This is quite the challenge. I am stumped. I feel like this might be one of those function.apply moments, but I am just guessing.

Haha, it definitely gets the brain moving. Sometimes the simplest solutions are the hardest to see, like a tricky chord progression.

Yo I feel that. sometimes I’ll spend an hour trying to optimize something only to realize the original simple loop was fine.

Nice