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 where the input objects are keyed by the result of calling the fn on each of them.
Essentially, I have to write a function, "groupBy(array, callback)", returns an object where the following is returned.
For example:
var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
groupBy(list, function(i) { return i.id; });
Returns:
{
"102": [{id: "102", name: "Alice"}],
"205": [{id: "205", name: "Bob", title: "Dr."}],
"592": [{id: "592", name: "Clyde", age: 32}]
}
Example 2:
groupBy(list, function(i) { return i.name.length; });
Returns:
{
"3": [{id: "205", name: "Bob", title: "Dr."}],
"5": [{id: "102", name: "Alice"},
{id: "592", name: "Clyde", age: 32}]
}
I'm still quite new to callback functions, and would like some tips/advice to simply get started. Even links to good tutorials would be greatly appreciated.
Answer
Solution with pure JS:
var list = [{
id: "102",
name: "Alice"
},
{
id: "205",
name: "Bob",
title: "Dr."
},
{
id: "592",
name: "Clyde",
age: 32
}
];
function groupBy(array, callback) {
return array.reduce(function(store, item) {
var key = callback(item);
var value = store[key] || [];
store[key] = value.concat([item]);
return store;
}, {})
}
console.log('example 1: ', groupBy(list, function(i) { return i.id; }));
console.log('example 2: ', groupBy(list, function(i) { return i.name.length; }));
No comments:
Post a Comment