Overview
Implement countBy(array, iteratee) that returns an object whose keys are the result of running each element through iteratee and values are the count.
Examples
countBy([6.1, 4.2, 6.3], Math.floor); // { '4': 1, '6': 2 }Solution
Reveal solution
function countBy(array, iteratee) {
const result = {};
for (const item of array) {
const key = String(iteratee(item));
result[key] = (result[key] || 0) + 1;
}
return result;
}count-by.js
Count By
mediumcodingJavaScriptArrays
Overview
Implement countBy(array, iteratee) that returns an object whose keys are the result of running each element through iteratee and values are the count.
Examples
countBy([6.1, 4.2, 6.3], Math.floor); // { '4': 1, '6': 2 }Solution
Reveal solution
function countBy(array, iteratee) {
const result = {};
for (const item of array) {
const key = String(iteratee(item));
result[key] = (result[key] || 0) + 1;
}
return result;
}NameTopicDifficulty
103 of 103 problems