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?

4 Answers 4

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

Comments

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

Comments

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

1 Comment

Thanks for the underscore.js method. I was wondering if there was something shorter than reduce suppose not. Btw, check out lodash.js a higher-performance, either compatible (or more consistent drop-in).
0

You need grouping. See jQuery Table Plugin with Group By

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.