JS分组

71 阅读1分钟
export function groupBy(array, f) {
  const groups = {};
  array.forEach(function (o) {
    //注意这里必须是forEach 大写
    const group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });

  return Object.keys(groups).map(function (group) {
    return groups[group];
  });
}

使用: aaa:要分组的数组 key:分组key

    let innerList = groupBy(aaa, (item) => {
      return [item.key];
    });
    let newList = innerList.map((item) => {
      // 遍历分组几条数据几条明细
      for (let i = 1; i < item.length; i++) {
        if (item[0].detail) {
          item[0].detail = item[0].detail.concat(item[i].detail);
        }
      }
      return item[0];
    });