[Solved] jQuery: count array elements by value

I have an array of elements assembled by:

timeArray = [];
$('.time_select').each(function(i, selected) {
  timeArray[i] = $(selected).val();

where .time_select is a class on a group of different HTML select tags.

What I’d like to do is count the number of times a specific value occurs in timeArray. Strangely enough, I haven’t found any concise solution… surely there’s a simple way to do this?

Enquirer: PlankTon


Solution #1:

timeArray = [];
occurs = {};
$('.time_select').each(function(i, selected) {
  timeArray[i] = $(selected).val();
  if (occurs[timeArray[i]] != null ) { occurs[timeArray[i]]++; }
  else {occurs[timeArray[i]] = 1; }
Respondent: Reigel

Solution #2:

You should try abstracting that into a function using the (under-used) $.each() function, I’d say.

function countElement(item,array) {
    var count = 0;
    $.each(array, function(i,v) { if (v === item) count++; });
    return count;

Then you can use it like so:

var a = ['foo','bar','foo'];
var b = countElement('foo',a); // should return 2

Solution #3:

JS doesn’t have many built-in functions for dealing with arrays. This is about as concise as it gets:

var count = 0;
for (var i = 0; i < timeArray.length; i++) {
    count += (timeArray[i] == targetValue);

If you’re willing to incur the overhead of an additional library, then underscore.js supplies a number of handy utility functions. Using underscore.js, the above code can be simplified to:

_(timeArray).reduce(function(m, num) {return m + (num == targetValue);}, 0);
Respondent: David Tang

Solution #4:

You need grouping. See jQuery Table Plugin with Group By

Respondent: Richard Schneider

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy