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
function groupBy(array, callback) {
var object = {};
for (var i = 0; i < array.length; i++) {
var item = array[i];
var key = callback(item);
if (object.hasOwnProperty(key)) {
object[key].push(item);
} else {
object[key] = [item];
}
}
return object;
};
var list = [
{ id: "102", name: "Alice"},
{ id: "205", name: "Bob", title: "Dr." },
{ id: "592", name: "Clyde", age: 32 }
];
var byId = groupBy(list, function(i) {
return i.id;
});
console.log(byId);
var byNameLength = groupBy(list, function(i) {
return i.name.length;
});
console.log(byNameLength);