JS 扩展数组方法

2024-12-04 17:14:31
Array.prototype.groupBy = function groupBy(key) {
  const hash = {},
    result = [];
  for (const el of this) {
    if (hash[el[key]]) {
      hash[el[key]].push(el);
    } else {
      result.push({
        key: el[key],
        values: (hash[el[key]] = [el]),
      });
    }
  }
  return result;
};

Array.prototype.key = function(key) {
  return this.map(el => el[key]);
};

Array.prototype.sum = function(key) {
  return this.reduce((total, el) => total + (key ? el[key] : el), 0);
};

Array.prototype.distinct = function() {
  return [...new Set(this)];
};