开发者

jQuery: count array elements by value

开发者 https://www.devze.com 2023-02-24 05:07 出处:网络
I have an array of elements assembled by: timeArray = []; $(\'.time_select\'开发者_开发技巧).each(function(i, selected) {

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?


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


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; }
});


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


You need grouping. See jQuery Table Plugin with Group By

0

精彩评论

暂无评论...
验证码 换一张
取 消