【问题标题】:group array and get count分组数组并获取计数
【发布时间】:2021-05-07 23:32:06
【问题描述】:

假设我有这样的数组:

[
   "foo",
   "bar",
   "foo"
   "bar",
   "bar",
   "bar",
   "zoom"
]

我想把它分组,这样我就可以得到这样的计数:

{
  "foo": 2,
  "bar": 4,
  "zoom": 1
}

有没有可以做到这一点的实用程序?

【问题讨论】:

  • 是的,有一个“实用程序”,请查看Array.prototype.reduce
  • Object.assign({}, ...Array.from(new Set(array), key => ({[key]: array.filter(v => v === key).length}))); - 效率低,但是没用

标签: javascript node.js


【解决方案1】:

解释:首先,我们create object(一个全新的空对象)。其次,使用spread operator,我们首先从现有数组中复制所有内容,并从中创建一个new array,并使用它来创建一个新的Set(Set 对象允许您存储unique值)并将其用作键,最后我们 filter 出我们的数组(在 length 属性的帮助下)查看特定 key 出现并设置了多少次到对象的 value。请记住,由于我们使用了Object.assign() 并将所有内容都放入其中,所以返回的是一个对象,其中包含我试图解释的所有结果(据我所知):) 我们还在这里使用了comma operator,它简单地评估其每个操作数(从左到右)并返回最后一个操作数的值。

const arr = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"];

const data = Object.assign({}, ...Array.from(new Set(arr), key => ({[key]: arr.filter(value => value === key).length})));

console.log(data);

【讨论】:

    【解决方案2】:

    您可以通过reduce 以简洁的方式执行此操作:

    var arr = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom" ] 
    
    var result = arr.reduce((r,c) => (r[c] = (r[c] || 0) + 1, r), {})
    
    console.log(result)

    如果您使用lodash_.countBy,它会变得非常可爱:

    var arr = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom" ] 
    
    var result = _.countBy(arr);
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    【讨论】:

      【解决方案3】:

      是的,您可以将您的数组reduce() 指向一个带有键和计数的对象,如下所示:

      const input = [
        "foo",
         "bar",
         "foo",
         "bar",
         "bar",
         "bar",
         "zoom"
      ];
      const result = input.reduce((total, value) => {
           total[value] = (total[value] || 0) + 1;
           return total;
      }, {});
      console.log(result);

      希望对你有帮助!

      【讨论】:

        【解决方案4】:

        您可以使用数组对象上可用的reduce() 方法来实现此分组。所以,类似这样的东西可能会实现你所追求的:

            var input = [
               "foo",
               "bar",
               "foo",
               "bar",
               "bar",
               "bar",
               "zoom"
            ]
            
            // Iterate the input list and construct a grouping via a "reducer"
            var output = input.reduce(function(grouping, item) {
            
              // If the current list item does not yet exist in grouping, set 
              // it's initial count to 1
              if( grouping[item] === undefined ) {    
                grouping[item] = 1;
              }
              // If current list item does exist in grouping, increment the 
              // count
              else {
                grouping[item] ++;
              }
            
              return grouping;
            
            }, {})
            
            console.log(output)

        【讨论】:

          【解决方案5】:

          只需使用函数Array.prototype.reduce

          let array = [   "foo",   "bar",   "foo",   "bar",   "bar",   "bar",   "zoom"],
              result = array.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), Object.create(null));
          
          console.log(result);
          .as-console-wrapper { max-height: 100% !important; top: 0; }

          【讨论】:

          • o/w 人们认为某处有一个名为b 的变量
          • 您还应该提及comma operator 以及它是如何工作的……如果您不解释或链接到它,很多人将无法理解语法。
          • 如果有人像我一样对, Object.create(null) 部分感到困惑,逗号使用comma operator 返回一个空对象。使用Object.create(null) 而不是{} 来创建object with no prototype
          • 请采纳@bendataclear 的建议,它有效且更清晰。 array.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), {})
          【解决方案6】:

          是的,我猜是 Array.prototype.reduce,它只是:

            const map = list.reduce((a, b) => {
                      a[b] = a[b] || 0;
                      return ++a[b], a;
                    }, {});
          

          想知道是否有不那么冗长的方式。

          【讨论】:

            猜你喜欢
            • 2021-11-08
            • 2013-03-27
            • 1970-01-01
            • 1970-01-01
            • 2016-01-03
            • 2021-10-30
            • 2015-05-26
            • 1970-01-01
            相关资源
            最近更新 更多