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 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 the number of occurrences of each item in an array?
no need to use jQuery for this task — this example will build an object with the amount of occurencies of every different element in the array in O(n)
var occurrences = { };
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}
console.log(occurrences); // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']); // 2
Example fiddle
You could also use Array.reduce to obtain the same result and avoid a for-loop
var occurrences = arr.reduce(function(obj, item) {
obj[item] = (obj[item] || 0) + 1;
return obj;
}, {});
console.log(occurrences); // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']); // 2
Example fiddle
count the number of occurrence of each element in an array (in php)
As mentioned in the comments array_count_values() is the optimal solution in php. But you must write it out aka show your understanding on how to search an array its rather simple as well.
$a=['a','b','a','c','a','d'];
$output=[];
for($i = 0; $i < count($a); $i++){
if(!isset($output[$a[$i]])){
$output[$a[$i]] = 1;
}
else{
$output[$a[$i]] = $output[$a[$i]] + 1;
}
}
var_dump($output);
//output
array(4) {
["a"] => int(3)
["b"] => int(1)
["c"] => int(1)
["d"] => int(1)
}
Count the number of occurrences of each item in an array and regex
You can do it like this:
var data =
[
{
"Id": "10",
"FileName": "TechnicalBook_2021-08-26T12:36:48Z",
"Book": "ABC P1",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "11",
"FileName": "SocialBook_2021-08-26T12:36:48Z",
"Book": "XYZ P1",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "12",
"FileName": "TechnicalBook_2021-08-26T15:36:48Z",
"Book": "ABC P2",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "13",
"FileName": "SocialBook_2021-08-26T15:36:48Z",
"Book": "XYZ P2",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "14",
"FileName": "SocialBook_2021-08-26T17:36:48Z",
"Book": "XYZ P3",
"Location": "USA",
"LastModified": "2021-08-26T17:36:48Z"
}
]
var prefixesAll = data.map(a => a.FileName.split('_')[0]);
var prefixesUnique = [...new Set(prefixesAll)];
var prefixCounts = prefixesUnique.map(a => ({
"FileName": a,
"Count": data.filter(b => b.FileName.startsWith(a)).length
}));
console.log(prefixesAll);
console.log(prefixesUnique);
console.log(prefixCounts);
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 each array item occurrence and return result as an object
Array.prototype.reduce()
seems to be pretty close to what you're looking for:
const src = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'],
result = src.reduce((acc,color) => (acc[color]=(acc[color]||0)+1, acc), {})
console.log(result)
.as-console-wrapper{min-height:100%;}
Counting occurrences of particular property value in array of objects
A simple ES6 solution is using filter
to get the elements with matching id and, then, get the length of the filtered array:
const array = [ {id: 12, name: 'toto'}, {id: 12, name: 'toto'}, {id: 42, name: 'tutu'}, {id: 12, name: 'toto'},];
const id = 12;const count = array.filter((obj) => obj.id === id).length;
console.log(count);
Related Topics
How Should Look a Application.Scss File in Ruby
Slow Assets Compilation in Development Mode
Uint8Array to String in JavaScript
How Persistent Is Localstorage
How to Scrape Data Using Ruby Which Is Generated by a JavaScript Function
How to Get the Nth Occurrence in a String
How to Show Modal Window in Controller's Action
Browser-Independent Way to Detect When Image Has Been Loaded
Best Way to Display Flash Notices in Rails
Can Mustache Templates Do Template Extension
Why Doesn't Decodeuri("A+B") == "A B"
How to Get the Selected Radio Button Value Using Js
Losing "This" Context in JavaScript When Passing Around Members
Send a File as Multipart Through Xmlhttprequest
Dynamically Loading a Typescript Class (Reflection for Typescript)