通过传递回调函数返回新对象

时间:2018-01-28 16:00:38

标签: javascript algorithm logic

我需要实现一个给定多个对象数组的函数:

var list = [
  {id: "102", name: "Alice"},
  {id: "205", name: "Bob", title: "Dr."},
  {id: "592", name: "Clyde", age: 32}];

必须返回对象属性回调函数要求的内容:

{
  "3": [{id: "205", name: "Bob", title: "Dr."}],
  "5": [{id: "102", name: "Alice"},
        {id: "592", name: "Clyde", age: 32}]
 }

groupBy(list, function(i) { return i.name.length; });

例如:这个回调要求返回每个对象的name.length加上原始对象作为其值,如果它们相同,则将它返回到同一个数组中。



var list = [
  {id: "102", name: "Alice"},
  {id: "205", name: "Bob", title: "Dr."},
  {id: "592", name: "Clyde", age: 32}];

function groupBy(arr, cb) {
  var newObj = {};
  var newArr = [];
  
  for (key of arr) {
    newObj = cb(key);
  }
  return newObj;
}

groupBy(list, function(i) { return i.id; });




我没有太多自己的解决方案,而且我已经撞墙了。如果你们/ gals会帮助我,我会非常感激。

干杯

1 个答案:

答案 0 :(得分:1)

您需要为每个新密钥创建一个空数组,您想要分组。

将实际对象推送到此数组。

function groupBy(array, cb) {
    var result = {},
        key;
  
    for (object of array) {
        key = cb(object);
        result[key] = result[key] || [];
        result[key].push(object);
    }
    return result;
}

var list = [{ id: "102", name: "Alice" }, { id: "205", name: "Bob", title: "Dr." }, { id: "592", name: "Clyde", age: 32 }];

console.log(groupBy(list, function(o) { return o.name.length; }));
console.log(groupBy(list, function(o) { return o.id; }));
.as-console-wrapper { max-height: 100% !important; top: 0; }