【问题标题】:How to make `groupBy` with native javascript如何使用本机 javascript 制作`groupBy`
【发布时间】:2018-08-27 15:55:07
【问题描述】:

如何用原生javascript实现groupBy

groupBy的定义】 创建一个由通过 iteratee 运行集合的每个元素的结果生成的键组成的对象。分组值的顺序由它们在集合中出现的顺序决定。每个键对应的值是负责生成键的元素数组。使用一个参数调用迭代对象:(值)。

【期待输出】 groupBy([6.1, 4.2, 6.3], Math.floor); // => { '4': [4.2], '6': [6.1, 6.3] } groupBy(['one', 'two', 'three'], 'length'); // => { '3': ['one', 'two'], '5': ['three'] }

【问题讨论】:

  • 那么问题出在哪里?
  • @Sirko 我想用原生 javascript 制作 groupBy,而不是来自 lodash
  • 不写确切的代码,我认为这最多需要10行代码:一个循环,一个if和一些赋值。

标签: javascript collections ecmascript-6 group-by lodash


【解决方案1】:

您可以将Array.reduce() 与对象一起使用来收集物品。键是通过将迭代对象应用于项目来创建的。

iteratee可以是字符串也可以是函数,所以我们需要检查类型,如果是字符串create函数,从item中提取属性。

集合可以是数组也可以是对象,我们可以使用Object.values()来获取数组。

const groupBy = (collection, iteratee = (x) => x) => {
  const it = typeof iteratee === 'function' ? 
    iteratee : ({ [iteratee]: prop }) => prop;

  const array = Array.isArray(collection) ? collection : Object.values(collection);

  return array.reduce((r, e) => {
    const k = it(e);
    
    r[k] = r[k] || [];
    
    r[k].push(e);
    
    return r;
  }, {});
};

console.log(groupBy([6.1, 4.2, 6.3], Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }
 
console.log(groupBy(['one', 'two', 'three'], 'length')); // => { '3': ['one', 'two'], '5': ['three'] }

console.log(groupBy({ a: 6.1, b: 4.2, c: 6.3 }, Math.floor)); // => { '4': [4.2], '6': [6.1, 6.3] }

【讨论】:

    【解决方案2】:

    您可以使用reduce 并公开一个通用按键分组函数

    function groupBy(arr, groupByKeyFn )
    {
       return arr.reduce( (acc, c) => {
           var key = groupByKeyFn(c);
           acc[key] = acc[key] || [];
           acc[key].push(c)
           return acc;
       }, [])
    }
    

    现在你可以把这个函数当作

    var arr1 = [6.1, 4.2, 6.3];
    var arr2 = ['one', 'two', 'three'];
    
    console.log( groupBy(arr1, s => Math.floor(s) ) );
    console.log( groupBy(arr2, s => s.length ) );
    

    演示

    function groupBy(arr, groupByKeyFn) {
      return arr.reduce((acc, c) => {
        var key = groupByKeyFn(c);
        acc[key] = acc[key] || [];
        acc[key].push(c)
        return acc;
      }, {})
    }
    
    var arr1 = [6.1, 4.2, 6.3];
    var arr2 = ['one', 'two', 'three'];
    
    console.log( groupBy(arr1, s => Math.floor(s) ) );
    console.log( groupBy(arr2, s => s.length ) );

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2021-12-27
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多