Overview
Implement groupBy(array, iteratee) — groups elements into arrays keyed by the result of iteratee.
Examples
groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] }Solution
Reveal solution
function groupBy(array, iteratee) {
const result = {};
for (const item of array) {
const key = String(iteratee(item));
if (!result[key]) result[key] = [];
result[key].push(item);
}
return result;
}group-by.js
Group By
mediumcodingJavaScriptArrays
Overview
Implement groupBy(array, iteratee) — groups elements into arrays keyed by the result of iteratee.
Examples
groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] }Solution
Reveal solution
function groupBy(array, iteratee) {
const result = {};
for (const item of array) {
const key = String(iteratee(item));
if (!result[key]) result[key] = [];
result[key].push(item);
}
return result;
}NameTopicDifficulty
103 of 103 problems