How to count certain elements in array?

Leem :

I have an array:

[1, 2, 3, 5, 2, 8, 9, 2]

I would like to know how many 2s are in the array.

What is the most elegant way to do it in JavaScript without looping with for loop?

Thor Jacobsen :

Very simple:

var count = 0;
for(var i = 0; i < array.length; ++i){
    if(array[i] == 2)
        count++;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to count certain elements in an object array in JavaScript?

Count elements in an array over a certain value

Stuck on getting total count and count of certain elements of an array

How to change a certain count of numpy matrix elements?

How do I efficiently count elements less than a certain value in a sorted array?

How to count the elements in an Array in Ruby

How to Count Matched array elements

Count how many elements in array

How to count array elements in mongo

Swift / Populate UITableView with Array.count of elements matching certain condition

count elements falling within certain thresholds in array in matlab?

How to count values in a certain range in a Numpy array?

How to count number of a certain element there are in an array?

How to get certain elements of an array in laravel?

How to apply rules to only certain elements in array

How to access certain elements in Matlab structure array

how to count how many elements have a certain class

How do I count the last elements in a list after a certain element?

Redis: How do I count the elements in a stream in a certain range?

Count how many initial elements in Pandas Series equal to a certain value?

How to count the number of elements of an arraylist with a certain term/word?

How do you count the elements of an array in java

How can I count the number of elements in an array?

How to count adjacent recurring elements in an array?

how to count duplicate elements in array in java

How to count `false` elements of the Array of Arrays

In Rails, how to group by count of elements in array field?

How to count array duplicate elements in MongoDB

How to count frequency of elements in a bigquery array field