0

我有一个看起来有点像这样的对象数组

 [ {
      "created_date" : "2013-08-12T06:25:00",
      "descriptor" : "Noise, Barking Dog (NR5)"
    },
    {
      "created_date" : "2013-08-17T06:25:00",
      "descriptor" : "Noise, Barking Dog (NR5)"
    },
    {
      "created_date" : "2013-08-17T02:25:00",
      "descriptor" : "Noise, Barking Dog (NR5)"
    },
    {
      "created_date" : "2013-08-12T06:25:00",
      "descriptor" : "Loud Music"
    },
    {
      "created_date" : "2013-08-17T06:25:00",
      "descriptor" : "Loud Music"
    },
    {
      "created_date" : "2013-08-17T02:25:00",
      "descriptor" : "Construction Noise"
    },
    {
      "created_date" : "2013-08-17T02:25:00",
      "descriptor" : "Construction Noise"
    }]

问题是我如何计算有多少“描述符”类别及其名称我应该如何使用 D3 或 jquery 来解决这个问题。基本上这个想法是形成不同的群体

4

3 回答 3

2

您可以使用 d3d3.map()将每个映射descriptor到其出现的次数。

var map = d3.map();
data.forEach(function(d) {
    var descriptorCount = map.get(d.descriptor);
    map.set(d.descriptor, descriptorCount === undefined ? 1 : ++descriptorCount);
});
console.log(map); // {Noise, Barking Dog (NR5): 3, Loud Music: 2, Construction Noise: 2}

小提琴

于 2013-08-22T20:16:22.173 回答
1
var UniqueDescriptors = "";
for (var i =0; i<array.length;i++) {
    var obj = array[i];
    if (obj.descriptor && UniqueDescriptors.indexOf(obj.descriptor) == -1) {
        UniqueDescriptors += obj.descriptor + '|';
    }
}
// this returns just the number
//return (UniqueDescriptors.split('|').length - 1);
// this returns an array of the different descriptors if you need the names. you also can count the number by accessing the length property
return UniqueDescriptors.split('|').pop();

当然,这个脚本的明显缺陷是它假定描述符值中没有管道。

于 2013-08-22T18:12:35.430 回答
0

只需遍历数组并收集每个描述符:

var descriptors = (function(data) {
    var seen = {};
    data.forEach(function(obj) {
        seen[obj.descriptor] = true;
    });
    return Object.keys(seen);
}(data));

要获取唯一描述符的数量,只需获取数组的长度:

descriptors.length

如果您需要支持不支持Object.keys或的旧版浏览器Array#forEach

var descriptors = (function(data) {
    var seen = {};
    var descriptors = [];
    for (var i = 0, l = data.length; i < l; i++) {
        var descriptor = data[i].descriptor;
        if (!seen[descriptor]) {
            descriptors.push(descriptor);
            seen[descriptor] = true;
        }
    }
    return descriptors;
}(data));
于 2013-08-22T20:27:41.680 回答