FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Count By

15mins

Implement a function countBy(array, iteratee) that creates an object where the keys are generated by running each element of array through the provided iteratee function.
The values of the object represent how many times each key was returned.

Arguments:

  • array (Array): The array to iterate over.
  • iteratee (Function): A function invoked per element, receiving the element as its only argument.

Returns:

  • Object: An object where each key is the result of iteratee and its value is the count of occurrences.

Examples:

countBy([6.1, 4.2, 6.3], Math.floor); // => { '4': 1, '6': 2 } countBy([{ n: 3 }, { n: 5 }, { n: 3 }], (o) => o.n); // => { '3': 2, '5': 1 } countBy([], (o) => o); // => {} countBy([{ n: 1 }, { n: 2 }], (o) => o.m); // => { undefined: 2 }

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests