jQuery:按值计算数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5615916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: count array elements by value
提问by PlankTon
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.
where.time_select
是一组不同 HTML 选择标签上的类。
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?
我想做的是计算特定值在timeArray
. 奇怪的是,我还没有找到任何简洁的解决方案......肯定有一种简单的方法可以做到这一点?
回答by Richard Neil Ilagan
You should try abstracting that into a function using the (under-used) $.each()
function, I'd say.
$.each()
我会说,您应该尝试使用(未充分利用的)函数将其抽象为一个函数。
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
回答by Reigel
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; }
});
回答by David Tang
JS doesn't have many built-in functions for dealing with arrays. This is about as concise as it gets:
JS 没有很多处理数组的内置函数。这是最简洁的:
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.jssupplies a number of handy utility functions. Using underscore.js, the above code can be simplified to:
如果您愿意承担额外库的开销,那么underscore.js提供了许多方便的实用程序函数。使用underscore.js,上面的代码可以简化为:
_(timeArray).reduce(function(m, num) {return m + (num == targetValue);}, 0);
回答by Richard Schneider
You need grouping. See jQuery Table Plugin with Group By