ZeiZei
ZeiZei

Reputation: 419

Count value frequencies in an array with jQuery

I have a form with several multiple-choice questions on a page and using serializeArray gives me an array like

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

and so on (each question have answer options a, b and c).

How can I count the frequency of each answer (a, b and c) in the array and have the counts as variables (a = 2, b = 1 in the case above)?

Upvotes: 2

Views: 1303

Answers (5)

Samuel
Samuel

Reputation: 2156

Compact jQuery solution:

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

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

Which gives you in the end:

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

Upvotes: 0

Axel Amthor
Axel Amthor

Reputation: 11096

simple:

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] ++;
}

should give :

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

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You can iterate the answer array and keep the count in seperate map where answer value is the key. See below code -

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>

Upvotes: 0

Remy Grandin
Remy Grandin

Reputation: 1686

Something like that :

var countArray = {}

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

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

Upvotes: 0

Magus
Magus

Reputation: 15104

You don't need jQuery at all for that.

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}

Upvotes: 5

Related Questions