I have a JavaScript task where I have to implement a function \"groupBy\", which, when given an array of objects and a function, returns an object w
var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
console.log(groupBy(list, function(i) { return i.id; }));
console.log(groupBy(list, function(i) { return i.name.length; }));
Here's a link to working example: https://codepen.io/pablo-tavarez/pen/NwjrEZ?editors=0012
function groupBy(list, callback) {
var output = {};
var key
, i = 0;
// iterate over list of objects
for ( ; i < list.length; i++ ) {
// pass the current item to callback and get (current) key
key = callback(list[i]);
if (output[key]) {
// handle duplicate keys without overriding -- (optionally make all key value Arrays)
output[key] = [output[key]];
output[key].push(list[i]);
}
else {
output[key] = list[i];
}
}
return output;
}