天天看点

来看看javascript新增的两个数组实例方法group()和groupToMap()

作者:橡树果前端工作室

javascript新增了两个数组实例方法

Array.prototype.group()

Array.prototype.groupToMap()

目前这两个方法都是实验性的,不建议用于生产环境

目前只有 Safari >= 16.4 版本支持

接下来我们来看看这两个方法的作用和如何使用

Array.prototype.group()

该方法根据提供的毁掉函数返回的字符串值,将调用数组的元素分组。返回的对象具有每个组的单独属性的元素数组。

group(callbackFn)
group(callbackFn, thisArg)           

callbackFn

为数组中的每个元素执行的函数,需要返回可以被转换为属性键的值,用于指示当前元素所处的分组,该函数拥有3个参数

  • element

数组中当前正在处理的元素。

  • index

正在处理的元素在数组中的索引。

  • array

调用了 group() 的数组本身。

thisArg(可选)

执行 callbackFn 时用作 this 的值

使用示例

  • 常规使用
const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];

const result = inventory.group(({ type }) => type);

/* 结果是:
{
  vegetables: [
    { name: 'asparagus', type: 'vegetables', quantity: 5 },
  ],
  fruit: [
    { name: "bananas", type: "fruit", quantity: 0 },
    { name: "cherries", type: "fruit", quantity: 5 }
  ],
  meat: [
    { name: "goat", type: "meat", quantity: 23 },
    { name: "fish", type: "meat", quantity: 22 }
  ]
}
*/
           
  • 指定分组的键值
function myCallback({ quantity }) {
  return quantity > 5 ? "ok" : "restock";
}

const result2 = inventory.group(myCallback);

/* 结果是:
{
  restock: [
    { name: "asparagus", type: "vegetables", quantity: 5 },
    { name: "bananas", type: "fruit", quantity: 0 },
    { name: "cherries", type: "fruit", quantity: 5 }
  ],
  ok: [
    { name: "goat", type: "meat", quantity: 23 },
    { name: "fish", type: "meat", quantity: 22 }
  ]
}
*/
           
  • 在稀疏数组上使用 group()
console.log([1, , 3].group((x) => x)); // { 1: [1], undefined: [undefined], 3: [3] }
// 也可以使用filter去除空元素
console.log([1, , 3]。filter(Boolean).group((x) => x)); // { 1: [1], 3: [3] }           
  • 在array-like上使用
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
};
console.log(Array.prototype.group.call(arrayLike, (x) => x % 2));
// { 0: [2, 4], 1: [3] }           

类似的数据处理场景还是挺常见的,所以这个方法还是比较实用的

Array.prototype.groupToMap()

该方法和 Array.prototype.group() 作用类似,唯一的区别是返回的是一个 Map 结构

例如

console.log([1, , 3].groupToMap((x) => x));
// Map { 1 => [1], undefined => [undefined], 3 => [3] }           

需要注意的是,上面两个方法返回的结果中的元素都不是 深拷贝

继续阅读