【问题标题】:Get count of most common property-value in a list of json-objects [duplicate]获取json对象列表中最常见的属性值的计数[重复]
【发布时间】:2023-04-03 19:55:01
【问题描述】:

给定数据

var data = [
    {
        "a" : "x"
        ... (other properties)
    },
    {
        "a" : "x"
        ... (other properties)
    },
    {
        "a" : "y"
        ... (other properties)
    },
]

最常见的“a”属性值的计数是 2,(对于“x”)。

现在,从data 获取此信息最干净的方法是什么?

我认为可能有一种很好的方法来生成不同计数的数组,即在这种情况下为[ 2 , 1 ],然后在此运行Math.max(...array)

但我似乎找不到这样做的干净方法?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    var data = [{
        a: "x"
      },
      {
        a: "x"
      },
      {
        a: "y"
      },
    ]
    
    var countPropertyValues = {};
    data.forEach(function(obj) {
      if (countPropertyValues.hasOwnProperty(obj.a)) {
        countPropertyValues[obj.a]++;
      } else {
        countPropertyValues[obj.a] = 1;
      }
    });
    
    console.log(countPropertyValues);
    
    var maxPropertyOccurence=0;
    var maxPropertyValue;
    
    for(var property in countPropertyValues){
    
        if(countPropertyValues[property]>maxPropertyOccurence){
          maxPropertyOccurence=countPropertyValues[property];
          maxPropertyValue=property;
        }
    }
    
    console.log(maxPropertyOccurence);
    console.log(maxPropertyValue);

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 2017-09-22
      • 2014-09-03
      • 1970-01-01
      • 2012-11-11
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      相关资源
      最近更新 更多