kdu*_*bss 5 javascript callback
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}]
}
Run Code Online (Sandbox Code Playgroud)
我对回调函数还是很陌生,并且想要一些提示/建议来简单地开始。即使是好的教程的链接也将不胜感激。
这是reduce()一条单行线。Reduce 允许您循环遍历数组并根据其回调逻辑附加到新对象。在这个函数中a(对于累积)是我们正在制作的对象,c(对于当前项目)是循环中一次获取一个项目。
它在这里工作得特别简洁,因为传入了创建对象键的函数:
var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
function groupBy(list, Fn) {
return list.reduce((a, c) => (a[Fn(c)] ? a[Fn(c)].push(c) : a[Fn(c)] = [c], a), {})
}
var t = groupBy(list, function(i) { return i.id; });
console.log(t)
var l = groupBy(list, function(i) { return i.name.length; });
console.log(l)Run Code Online (Sandbox Code Playgroud)
纯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; }));Run Code Online (Sandbox Code Playgroud)