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 are 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 how often a particular value appears in an array
PHP has a function called array_count_values
for that.
Example:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output:Array
(
[1] => 2
[hello] => 2
[world] => 1
)
Finding out how many times an array element appears
- Keep a variable for the total count
- Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
- After the loop, total count contains the number of times the number you were looking for is in the array
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented asfunction countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array. 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)
Counting the number of times a value appears in an array
You're getting an index out of bounds error because of this section:
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Notice that you're iterating through 0
to SIZE - 1
(11
) when Count
only has a size of 4
.You can do this task pretty easily with LINQ though.
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var count = numbers
.GroupBy(e => e)
.Where(e => e.Count() == 4)
.Select(e => e.First());
So it groups the numbers by their value, we then refine the list to only include groups of 4, then select the first of each to be left with a collection of int
s.Here is a non-LINQ based solution using a Dictionary to store the count of numbers.
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var dictionary = new Dictionary<int, int>();
var numbersWithFour = new List<int>();
foreach (var number in numbers)
{
if (dictionary.ContainsKey(number))
dictionary[number]++;
else
dictionary.Add(number, 1);
}
foreach (var val in dictionary)
{
if (val.Value == 4)
{
numbersWithFour.Add(val.Key);
}
}
With a little modification to your program you can get some results.
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] { 15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44 };
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
// Set the size of Count to maximum value in numbers + 1
int[] Count = new int[9 + 1];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
// Use value from numbers as the index for Count and increment the count
Count[numbers[i]]++;
}
}
for (i = 0; i < Count.Length; i++)
{
// Check all values in Count, printing the ones where the count is 4
if (Count[i] == 4)
Console.WriteLine("{0}", i);
}
Output:7
9
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 How Many Times a Value Appears Php
array_count_values
, enjoy :-)
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
//basically we get the same array
foreach ($array as $data) {
$count[] = $data;
}
$vals = array_count_values($count);
print_r($vals);
Result:Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
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
Eachcount
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.
Java count occurrence of each item in an array
You could use a MultiSet
from Google Collections/Guava or a Bag
from Apache Commons.
If you have a collection instead of an array, you can use addAll()
to add the entire contents to the above data structure, and then apply the count()
method to each value. A SortedMultiSet
or SortedBag
would give you the items in a defined order.
Google Collections actually has very convenient ways of going from arrays to a SortedMultiset
.
Related Topics
Converting Float Decimal to Fraction
Magento Products by Categories
No Hint Path Defined for [Mail] Laravel 5.4
Get Calling File Name from Include()
PHP Datetime::Createfromformat Doesn't Parse Iso 8601 Date Time
How to Implement Ws-Security 1.1 in PHP5
How to Disable the Back Browser Button After User Press Logout and Destroy Session
Uploading Image from Android to PHP Server
How to Remove All Dtddwrappers and Labels on Zend Form Elements
Efficient Reloading Data/Pushing Data from Server to Client
Cannot Unpack Array with String Keys
How to Get the Session Id in Laravel
How to Prevent PHP Script Running More Than Once
Using PHP & Curl to Login to My Websites Form
How to Remove Exif from a Jpg Without Losing Image Quality
Create a Joomla! Article Programmatically