How to count certain elements in array?
Very simple:
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}
Count the number of times a same value appears in a javascript array
There might be different approaches for such purpose.
And your approach with for
loop is obviously not misplaced(except that it looks redundantly by amount of code).
Here is some additional approaches to get the occurrence of a certain value in array:
Using
Array.forEach
method:var arr = [2, 3, 1, 3, 4, 5, 3, 1];
function getOccurrence(array, value) {
var count = 0;
array.forEach((v) => (v === value && count++));
return count;
}
console.log(getOccurrence(arr, 1)); // 2
console.log(getOccurrence(arr, 3)); // 3Using
Array.filter
method:function getOccurrence(array, value) {
return array.filter((v) => (v === value)).length;
}
console.log(getOccurrence(arr, 1)); // 2
console.log(getOccurrence(arr, 3)); // 3
Count number of values in array with a given value
How about using array_count _values to get an array with everything counted for you?
Counting the occurrences / frequency of array elements
const arr = [2, 2, 5, 2, 2, 2, 4, 5, 5, 9];
function foo (array) {
let a = [],
b = [],
arr = [...array], // clone array so we don't change the original when using .sort()
prev;
arr.sort();
for (let element of arr) {
if (element !== prev) {
a.push(element);
b.push(1);
}
else ++b[b.length - 1];
prev = element;
}
return [a, b];
}
const result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')
console.log(arr)
How to count the number of elements in an array below/above a given number (javascript)
Use Array#reduce with an object { above: 0, below: 0 }
as initial value. On each iteration check each number against the media, and accordingly add 1 to above/below.
Note: This is an array of strings. I've converted them manually to numbers. I also assume that a number that equals the median should be added to below. If you want to skip this numbers, change the comparison to <
.
var array = [3.1, 1, 2.2, 5.1, 6, 7.3, 2.1, 9];
var median = 5.25;
var counts = array.reduce(function(s, n) { s[n <= median ? 'below' : 'above'] += 1; return s;}, { above: 0, below: 0 });
console.log(counts);
How do I count the occurrence of a certain item in an ndarray?
Using numpy.unique
:
import numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)
>>> dict(zip(unique, counts))
{0: 7, 1: 4, 2: 1, 3: 2, 4: 1}
Non-numpy method using collections.Counter
;
import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(a)
>>> counter
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})
Idiomatically find the number of occurrences a given value has in an array
reduce
is more appropriate here than filter
as it doesn't build a temporary array just for counting.
var dataset = [2,2,4,2,6,4,7,8];var search = 2;
var count = dataset.reduce(function(n, val) { return n + (val === search);}, 0);
console.log(count);
How do I count the occurrences of a list item?
If you only want a single item's count, use the count
method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Important: this is very slow if you are counting multiple different items
Each count
call goes over the entire list of n
elements. Calling count
in a loop n
times means n * n
total checks, which can be catastrophic for performance.
If you want to count multiple items, use Counter
, which only does n
total checks.
How to count number of values in array?
You could take a dynamic apporach and hand over the key of the object where you like to count a certain inner key.
function count(object, key, subKey) { const noObject = o => !o || typeof o !== 'object';
function subCount(object) { if (noObject(object)) return 0; if (subKey in object) return 1; return Object.values(object).reduce((s, o) => s + subCount(o), 0); }
if (noObject(object)) return 0; if (key in object) return subCount(object[key]); return Object.values(object).reduce((s, o) => s + count(o, key, subKey), 0);}
var data = { data: [{ alpha: "a", beta: "b", delta: { cat: "dog" }, gamma: { sierra: { data: [{ type: "alphabet", id: "a" }, { type: "alphabet", id: "b" }] } } }] };
console.log(count(data, 'sierra', 'id')); // 2
PHP - count specific array values
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
Related Topics
Print Numeric Values to Two Decimal Places
PHPdoc Type Hinting For Array of Objects
How to Post Pictures to Instagram Using API
How Do PHP Sessions Work? (Not "How Are They Used")
How to Test a Url For 404 in PHP
Remove Excess Whitespace from Within a String
How to Increase Maximum Execution Time in PHP
PHP Simplexml How to Save the File in a Formatted Way
PHP.Ini & Smtp= - How to Pass Username & Password
How to Properly Url Encode a String in PHP
A Non Well Formed Numeric Value Encountered
How to Call Shell Script from PHP That Requires Sudo
Error With PHP Mail(): Multiple or Malformed Newlines Found in Additional_Header
PHP Fatal Error: Cannot Redeclare Class
How to Write into a File in PHP