Skip to content

Latest commit

 

History

History
26 lines (25 loc) · 875 Bytes

0603.md

File metadata and controls

26 lines (25 loc) · 875 Bytes

如何用将一个数组中任意字段的不同对数组进行分类

const cate = (softewares) => {
  let childSoftwares = [];
  if (Array.isArray(softewares)) {
    // 拿到要分类的字段集合,放到数组中并去重
    let subName = Array.from(new Set(softewares.map(item => item.name)));
    subName.forEach((sub, i) => {
      softewares.forEach(item => {
        if (sub === item.name) {
          // 注意判断  undefined 只能有一层,childSoftwares[i].name 这些写会报错
          if (childSoftwares[i]) {
            // 判断如果有了当前项就可以给数组push了
           childSoftwares[i].array.push(item);
          } else {
            // 没有当前项就新创建一个
            childSoftwares[i] = {array: [item], name: sub};
          }
        }
      });
    });
  }
  return childSoftwares;
};