FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Group By

20mins

Implement a function groupBy(array, keyOrFn) that groups elements of an array into an object based on a function or property name.

The function should:

  • Accept an array of values.
  • Accept a key function or a property name string.
  • Return an object where each key corresponds to the result of the function or property, and the value is an array of items that match that key.

Example

groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] } groupBy(['one', 'two', 'three'], 'length'); // { '3': ['one', 'two'], '5': ['three'] }

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests