高级前端手写代码【Q679】实现一个函数 groupBy

实现一个函数 groupBy

更多描述 类似 lodash.groupBy

groupBy(
  [
    { id: 1, name: "山月", sex: "male" },
    { id: 2, name: "张三", sex: "female" },
    { id: 3, name: "李四", sex: "female" },
  ],
  (x) => x.sex,
);

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 698

Author 回答者: shfshanyue

function groupBy(collection, by) {
  return collection.reduce((acc, x) => {
    if (acc[by(x)]) {
      acc[by(x)].push(x);
    } else {
      acc[by(x)] = [x];
    }
    return acc;
  }, {});
}

Author 回答者: heretic-G

function groupBy(data, filter) {
  const map = {};
  data.forEach((curr) => {
    const key = filter(curr);
    if (!map[key]) map[key] = [];
    map[key].push(curr);
  });
  return map;
}

Author 回答者: JoeWrights

function groupBy(arr = [], callback) {
  const obj = {};
  const keys = arr.map(callback);
  keys.forEach((key) => {
    obj[key] = [];
  });
 
  arr.forEach((ele) => {
    obj[callback(ele)].push(ele);
  });
 
  return obj;
}