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
Here is another approach using reduce:
var list = [{
id: "102",
name: "Alice"
},
{
id: "205",
name: "Bob",
title: "Dr."
},
{
id: "592",
name: "Clyde",
age: 32
}
];
function groupBy(list, callback) {
return list.reduce((acc, x) => {
const key = callback(x);
if (!acc[key]) {
return {
...acc,
[key]: [x]
}
}
return {
...acc,
[key]: [...acc[key], x]
}
}, {})
}
// callback functions
function nameLength(obj) {
return obj.name.length;
}
function objectProperty(obj) {
return obj.id
}
console.log('group by name length:', groupBy(list, nameLength));
console.log('group by Id:', groupBy(list, objectProperty));