2

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)?

1
  • Please show what you've tried Commented Oct 6, 2015 at 11:56

5 Answers 5

5

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}
Sign up to request clarification or add additional context in comments.

Comments

0

Something like that :

var countArray = {}

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

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

Comments

0

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>

Comments

0

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,
}

Comments

0

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.