3

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?

David Tang
  • 92,262
  • 30
  • 167
  • 149
PlankTon
  • 12,443
  • 16
  • 84
  • 153

4 Answers4

13

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
Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
5
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; }
});
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
2

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);
David Tang
  • 92,262
  • 30
  • 167
  • 149
  • Thanks for the underscore.js method. I was wondering if there was something shorter than `reduce` suppose not. Btw, check out [lodash.js](http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore) a higher-performance, either compatible (or more consistent drop-in). – karmakaze Apr 15 '13 at 05:49
0

You need grouping. See jQuery Table Plugin with Group By

Community
  • 1
  • 1
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73