gpt4 book ai didi

javascript - 根据回调函数对对象进行分组

转载 作者:行者123 更新时间:2023-11-29 20:57:40 25 4
gpt4 key购买 nike

<分区>

我有一个对象数组,需要根据给定的回调函数“排序”并放入另一个对象中。例如:

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;
)}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com