Skip to content

Instantly share code, notes, and snippets.

@jhsuZerion
Created August 29, 2018 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhsuZerion/8dbd175b7cffe9c72ea45fc56be8124b to your computer and use it in GitHub Desktop.
Save jhsuZerion/8dbd175b7cffe9c72ea45fc56be8124b to your computer and use it in GitHub Desktop.
Page-level JavaScript function to return the number of occurrences in an array of values
/**
* Return the number of occurrences in a list
* @param {Array} arr list of primitive values (string, numeric, boolean)
* @param {String|Numeric} x the value to be searched for
* @return {Int} the count of occurrences
*/
function countIf(arr,x) {
var count = 0;
if(arr && Array.isArray(arr)) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == x) count++;
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment