极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 实现一个函数 groupBy

更多描述

类似 lodash.groupBy (opens new window)

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

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 698 (opens new window)

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;
  }, {});
}
function groupBy(data, filter) {
  const map = {};
  data.forEach((curr) => {
    const key = filter(curr);
    if (!map[key]) map[key] = [];
    map[key].push(curr);
  });
  return map;
}
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;
}
Last Updated: 11/27/2021, 6:11:48 PM