Array.groupBy 在 Typescript e6 中可以与箭头函数一起使用

Array.groupBy in Typescript e6 can be use with arrow function

我正在尝试将一种方法转换为通用方法以与 JavaScript 中的箭头函数一起使用,但不知何故无法确定我应该如何转换它。 groupBy: <Map>(predicate: (item: T) => Map[]) => Map[];

Array.prototype.groupBy = function (predicate) {
return this.reduce(
    (entryMap, e) => entryMap.set(e.status, [...entryMap.get(e.status) || [], e]),
    new Map()
)};

我在此方法中收到的谓词类似于 ƒ (x) { return x.status; }

我想将此 e.status 替换为一些通用的,以便我可以像 arrayData.groupBy(x=>x.status) 一样使用它。 作为初学者,我无法弄清楚我应该怎么做。 我在 post @ 中找到了方法,post 由 @Arthur Tacca

编辑

提前致谢

链接问题中的代码根据 e.status 对对象进行分组。但是,在您的情况下 属性 是动态的。如果将 x => x.status 作为谓词参数传递,如何为 reduce 中的每个对象获取 e.status?您只需要使用 e 参数调用 predicate。因此,将所有 e.status 替换为 predicate(e)

Array.prototype.groupBy = function(predicate) {
  return this.reduce(
    (entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]),
    new Map()
  )
};

const arr = [{ status: 10, id: 1 }, { status: 10, id: 2 }, { status:20, id: 3 }],
      map = arr.groupBy(e => e.status)

console.log(map.get(10))
console.log(map.get(20))
console.log(map.get(30))

请注意extending native objects a bad practice。即使您将新项目添加到原型中,也请确保您使用 Object.defineProperty 添加,如下所示:

Object.defineProperty(Array.prototype, "groupBy", {
  value: function(predicate) {
    return this.reduce(
      (entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]),
      new Map()
    )
  },
  configurable: true,
  writable: true
});

如果您这样定义,enumerable 将被设置为 false。如果直接加上Array.prototype.groupBy = function(predicate){}enumerable会被设置为true,会show up in for..in loops.