Instances of an Array Element Count

Author: Theodore Odeluga

The source files for this project can be downloaded from here

This is a Node command line project and Node.js can be downloaded from here

Instructions for running a command line program with Node.js can be found here

Here's another useful technique for working with strings and arrays.

Counting the number of instances of certain characters in a string can be a helpful way to cut down on duplication.

This could even be the starting point of online spell checking program.

In the following code, we create a simple function to count the number of occurrences of a specific character in a given string.

We begin by creating an array with a random sample.

let occurences = ['an apple a day keeps the doctor away']

Next, we set up a list of variables.

let arrayasstring;
let j;
let k;
let splitit;
let count = 0;

Arrayasstring will contain the conversion of the occurences array to a string object.

j will equate to the entire length of splitit, the object containing arrayasstring (occurrences in string form), as processed by the split method.

k will iterate through splitit to find the character whose instances are being counted.

Splitit as mentioned, will contain the characters of arrayasstring broken up into separate elements.

Count will simply provide information on exacly how many instances of the tested character have been found.

Following the opening of character_count(), the program's only function, the first line of code converts the occurrences array to a string.

Splitit then breaks up this new object into separate elements.

J then comes along and captures the size of the whole object by applying the length property.

This in turn allows k to iterate across splitit using the value of j as the range.

In the example, the number of ocurrences for the character 'p' are being extracted.

Following the incrementation of count, the function definition is closed, called and the output displayed.

Here's the complete program for convenience.

let occurences = ['an apple a day keeps the doctor away']

let arrayasstring;
let j;
let k;
let splitit;
let count = 0;

function character_count(){
arrayasstring = occurences.toString();
splitit = arrayasstring.split("");
j = splitit.length;

for(k=0; k < j; k++){
   if(splitit[k] == 'p'){
      count++;
    }
  }
}

character_count();
console.log("The total number of occurences of the character 'p' are: " + count);

Conclusion

Tracking multiple instances of a character can enable everything from counting, removal and character swapping or changing. I hope this sample will prove to be a useful utility in your own programs. See what else you can do with it as you experiment with its capability. Thanks for reading and happy coding.