Asked 2 years ago
15 Apr 2022
Views 720
jignesh

jignesh posted

Javascript : How to count occurrence of certain elements in array?


var a=[1.2,3,"3",4,5];
a.search("3")//it should return total number of 3 in given array

how to count how many time element in the array in javascript ?

as per above example, I want to know how many 3 in the given array .
pratik

pratik
answered Apr 27 '22 00:00


 var a=[1.2,3,"3",4,5];


var countd=0;
for( i=0;i<=a.length;i++){ 
 
if(a[i]=="3"){ countd++;} 
 }
console.log(countd);

we use "for loop" to iterate with every element and it checks with the given value and the count increases every time the match is found.

above code run and print count of 3 in console log

lets make it dynamic function , so it will find the given element in the given array

function findgivenelement(array,elementtofind){
var countd=0;
    for( i=0;i<=array.length;i++){ 
           if(array[i]=="elementtofind"){ countd++;} 
    }
}
var a=[1.2,3,"3",4,5];

findgivenelement(a,"3");

above function work with only one dimensional array
sec8

sec8
answered Apr 27 '22 00:00

use forEach , to count occurrence of certain elements in array.

const array1 = ['a','a','a', 'b', 'c'];
var count=0;
array1.forEach(element =>  { (element=='a')?count++:'';});
alert(count);
Post Answer