数组计数中的唯一值

时间:2012-02-29 16:03:24

标签: javascript jquery arrays

我有一个类似下面的数组

var data = [
            ["1"," 101_30.1.101_34","0.0200112629","mm/s","[OK]"],
            ["1"," 101_30.1.101_35","0.0146548533","mm/s","[OK]"],
            ["1"," 101_30.1.101_45","0.0146548533","mm/s","[OK]"],
            ["1"," 101_42.2.101_43","0.0101406257","mm/s","[OK]"],
            ["2"," 102_17.3.102_38","5.1719756","mm/s","[WA]"],
            ["2"," 102_17.3.102_39","3.5886707","mm/s","[WA]"],
            ["2"," 102_17.3.102_44","9.4615074E-4","mm/s","[OK]"],
            ["2"," 102_40.4.102_41","4.8159785","mm/s","[OK]"],
            ["3"," 204_15","3.8374166","mA","[OK]"],
            ["4"," 501_11","1027.5156","RPM","[WA]"]
           ]

我想要做的是找到有多少独特阵列。实施例1 = 4,2 = 4,3 = 1,4 = 1

数据来自数据库,因此数组的数量总是可以改变。

以下是关于JsFiddle

的简单说明

1 个答案:

答案 0 :(得分:7)

尝试这样的事情:

var count = {};
$.each(data, function(){
    var num = this[0]; // Get number
    count[num] = count[num]+1 || 1; // Increment counter for each value
});
console.log(count); // {1: 4, 2: 4, 3: 1, 4: 1}