我有一系列对象,我需要"排序"并根据给出的回调函数放入另一个对象。例如:
var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
groupBy(list, function(i) { return i.name.length; });
应该返回:
{
"3": [{id: "205", name: "Bob", title: "Dr."}],
"5": [{id: "102", name: "Alice"},
{id: "592", name: "Clyde", age: 32}]
这是我到目前为止所得到的但是我被卡住了......
function groupBy(arr, cb) {
let result = {};
arr.forEach(function (obj) {
var group = [];
group.push(cb(i))
result[group].push(obj);
}
return result;
)}
答案 0 :(得分:1)
我将如何做到这一点:
function groupBy(arr, cb){
const res = {};
for(const el of arr){
const key = cb(el);
(res[key] || (res[key] = [])).push(el);
}
return res;
}
为什么它不起作用:
function groupBy(arr, cb) {
let result = {};
arr.forEach(function (obj) {
//That creates one group for each obj?
var group = [];
//group should contain the obj, not the key?
group.push(cb(i))
// Now you are accessing the result by an array as index??
// And try to push the object to it which will obvipusly fails as you never set result[group] to an array
result[group].push(obj);
}
return result;
//Typo??
)}
答案 1 :(得分:1)
您需要从return value
获取callback
并对此做出决定
var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
function groupBy(arr, cb) {
let result = {};
arr.forEach(function (obj) {
var group = [];
const length = cb(obj)
// if result[length] is undefined then create a new array with the current object
// else push into the existing array
result[length] ? result[length].push(obj) : result[length] = [obj];
})
return result;
}
console.log(groupBy(list, function(i) { return i.name.length}))
答案 2 :(得分:0)
使用数组reduce
功能。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];
const result = list.reduce((acc, curr) => {
const { name } = curr;
acc[name.length] = (acc[name.length] || []).concat(curr);
return acc;
}, {});
console.log(result);