使用jQuery计算数组中的值频率

时间:2015-10-06 11:53:43

标签: javascript

我在页面上有一个包含多个选择题的表单,使用serializeArray给我一个像

这样的数组
[
  {
    name: "question1",
    value: "a"
  },
  {
    name: "question2",
    value: "a"
  },
  {
    name: "question3",
    value: "b"
  }
]

等等(每个问题都有答案选项a,b和c)。

如何计算数组中每个答案(a,b和c)的频率并将计数作为变量(在上述情况下a = 2,b = 1)?

5 个答案:

答案 0 :(得分:4)

你根本不需要jQuery。

var array = [
  {
    name: "question1",
    value: "a"
  },
  {
    name: "question2",
    value: "a"
  },
  {
    name: "question3",
    value: "b"
  }
]

var counts = {};

array.forEach(function(element) {
    if (!counts[element.value]) {
        counts[element.value] = 0;
    }

    counts[element.value] += 1;
});

console.log(counts);

// Output :
// {"a" : 2, "b" : 1}

答案 1 :(得分:0)

类似的东西:

var countArray = {}

$.each(dataArray, function(index, value){
    if(countArray[value.value] == undefined)
        countArray[value.value] = 0;

    countArray[value.value]++;
});

答案 2 :(得分:0)

试试这个:您可以迭代答案数组并将计数保持在单独的地图中,其中答案值是关键。见下面的代码 -

var answerArray = [
  {
    name: "question1",
    value: "a"
  },
  {
    name: "question2",
    value: "a"
  },
  {
    name: "question3",
    value: "b"
  }
];

var countMap = {};
$.each(answerArray, function(k, v){
   countMap[v.value] = (countMap[v.value])? (parseInt(countMap[v.value])) + 1 : 1;
});

alert(JSON.stringify(countMap));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

答案 3 :(得分:0)

简单:

var answers = [
  {
    name: "question1",
    value: "a"
  },
  {
    name: "question2",
    value: "a"
  },
  {
    name: "question3",
    value: "b"
  }
]
var histogram = {};

for ( var n = 0; n <answers.length; n++ )
{
   if ( !histogram[answers[n].value] )
       histogram[answers[n].value] = 1;
   else
       histogram[answers[n].value] ++;
}

应该给:

{
   "a": 2,
   "b": 1,
}

答案 4 :(得分:0)

紧凑型jQuery解决方案:

var count = {a: 0, b: 0, c: 0};

$(array).map(function(){
    count[this.value]++;
});

最终给你的是:

{a: 2, b: 1, c: 0}