chevron_left
459 points
12 7 5

Javascript count occurrences in an array code example

Before finding the solution to the problem. Let us succinctly discuss about arrays, how to declare, intialize, and cycle through array elements.

Unlike other programming languages, Arrays in Javascript can store elements of dissimilar data types. The length of the array isn't fixed and elements aren't stored in adjoining locations. Elements of an array can be retrieved with the help of an index. Index is an integer value associated with each element. The index is an integer value and default indexing always starts from '0'. Thus the first element of an array will always have an index '0' and last element holds an index of value of array length minus 1.

Create an Array

let flowers=['rose','sunflower',''Mary','Lillies','Orchids'];

Accessing an array element using index

console.log(flowers[0]);
console.log(flowers[flowers.length-1]);

This will display the value 'rose' with index 0 and last element of array 'Orchids' with index '4'.

Iterating through Array

for(e in flowers)
console.log(e);

The above iteration on array will display the array elements

Each element of an array is traversed and printed. We have different methods to traverse through the array elements. Above mentioned example is just a one way.

After comprehending about arrays, now let us write a code snippet which solves our problem statement.

Solution :

let arr=['h','e','l','l','o'];
console.log("Length of array : " + arr.length);
let ch='l', count =0 ;
for(var i=0;i {
if(arr[i]== ch) count++;
}
console.log("Number of occurences of given character is : " + count);
for(e in arr)
{
if(arr[i]== ch) count++;
}
console.log("Number of occurences of given character is : " + count);

In the precursory example,

  • Intialized an array and a character variable whose occurences should be found.
  • A variable count is intialized with value 0.
  • for loop, cycles through each element of array and checks if the statement is true.
  • If the statement is true count variable is incremented.
  • Finally, the variable count has the number of frequencies of given character ch.

The output of the program is:


PS C:\Users\Desktop\All Automation notes\JavaScriptPrograms> node char.js
Length of array : 5
Number of occurences of given character is : 2
Number of occurences of given character is : 2

More Posts

Javascript program to count the number of occurrences in the array. Lalit Kumar - Sep 27, 2020
Javascript for loop array DivyaN - 3 days
Javascript count occurrences of character in string Jeevani - Jul 10
Count occurrences of character in string javascript amna - Oct 26, 2020
Javascript count number of occurrences in string amna - Oct 20, 2020
How to check if a button is clicked in javascript DivyaN - Oct 18
Remove duplicate characters in a string javascript DivyaN - Oct 13
Javascript parsedouble DivyaN - 1 day
Math.sum javascript DivyaN - 1 day
Javascript Hide button DivyaN - 1 day