0
点赞
收藏
分享

微信扫一扫

更为优雅的数据分组方式Array.prototype.groupBy

十里一走马 2022-01-14 阅读 69
原型模式

在平常的开发过程中,我们可能会遇到需要根据数组每一项(Object)的某个key进行归类的情况,虽然有实现的方式,但是都特别的难读和冗余。

不过,一个专门用来做数据分组的提案 Array.prototype.groupBy 已经到达 Stage 3 了!当然现在是无法使用的,还没正式的支持。

以前的方式有

for 循环、reduce、filter、等

Array.prototype.groupBy

假设一组数据:

const items = [
  {
    type: 'clothes',
    value: '👔',
  },
  {
    type: 'clothes',
    value: '👕',
  },
  {
    type: 'clothes',
    value: '👗',
  },
  {
    type: 'animal',
    value: '🐷',
  },
  {
    type: 'animal',
    value: '🐸',
  },
  {
    type: 'animal',
    value: '🐒',
  },
];

我们根据type进行分类成下面的格式:

  clothes: [
    {
      type: 'clothes',
      value: '👔',
    },
    {
      type: 'clothes',
      value: '👕',
    },
    {
      type: 'clothes',
      value: '👗',
    },
  ],
  animal: [
    {
      type: 'animal',
      value: '🐷',
    },
    {
      type: 'animal',
      value: '🐸',
    },
    {
      type: 'animal',
      value: '🐒',
    },
  ],
};

那么只需要一行代码

items.groupBy(({ type }) => type);

groupBy 的回调中一共有三个参数:

参数1:数组遍历到的当前对象
参数2:index 索引
参数3:原数组

const array = [1, 2, 3, 4, 5];

// groupBy groups items by arbitrary key.
// In this case, we're grouping by even/odd keys
array.groupBy((num, index, array) => {
  return num % 2 === 0 ? 'even': 'odd';
});

另外,你还可以用 groupByToMap,将数据分组为一个 Map 对象。

// groupByToMap returns items in a Map, and is useful for grouping using
// an object key.
const odd  = { odd: true };
const even = { even: true };
array.groupByToMap((num, index, array) => {
  return num % 2 === 0 ? even: odd;
});

// =>  Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }
举报

相关推荐

0 条评论