Blog
JavaScript Function that Takes in a String and Outputs an Object Literal that Counts Characters
Posted on June 24, 2015 in Algorithms, JavaScript by Matt Jennings
function countChar(string) {
// Create an empty object
var countCharObj = {};
// For loop to iterate over a string
for(var i = 0; i < string.length; i++) {
/*
If the "countCharObj" does NOT have a property from
the "string" that is being iterated on
create a new "countCharObj" property with
property name from the iterated "string" and
set the property's value to 1
*/
if(!countCharObj.hasOwnProperty(string[i])) {
countCharObj[string[i]] = 1;
}
else {
/*
If an "countCharObj" property already exists then
AND has a value of 1 then increment it's value
*/
countCharObj[string[i]]++;
}
}
return countCharObj;
}
var myString = "mycoolstring";
/*
Output of the code below is properties of the "countCharObj" object:
c: 1,
g: 1,
i: 1,
l: 1,
m: 1,
n: 1,
o: 2,
r: 1,
s: 1,
t: 1,
y: 1
*/
console.log(countChar(myString));
Leave a Reply