Counting Objects
Each word has a number of letters in it. Some letters appear more than once in a word. We can definitely count the number of letters in a word because most words, if not all, are short. But what if the word we have is very long? We can miscount and that forces us to start the count over again. We shall see how to do that. In this article, I will show how to count the number of each letter in a word. The question is, given a word,
const word = 'pneumonoultramicroscopicsilicovolcanoconiosis'
print an object such that it shows how many times a letter appeared in the word. In other words, we want the answer to be in this form:
{
p: 2,
n: 4,
e: 1,
...
}.
We will use name a function called “countLetters”. The first step we want to do is to split the word into an array. To do that, we use the “split()”. It will split the word
const word = 'pneumonoultramicroscopicsilicovolcanoconiosis'
into
letters = ['p', 'n', 'e', ...].
The split() part is
const letters = word.split('').
Because we are looking at an individual word, we want to split between each letter. If there were a space between the quotes, the word will not split into an array.
We need to define an empty object
var obj = {}.
The next step is to iterate through the array “letters”, but we have a problem: the object is empty. So what do we need to do so that we can insert something into our object? The answer is to use “hasOwnProperty()” to see whether a key, or in this case, a letter, exists or not. The way to write this is
if(obj.hasOwnProperty(letters[x]) === false){
obj[letters[x]] = 0
}.
This is important because if we forget that, we will instead get
{
p: undefined,
n: undefined,
e: undefined,
...
}.
We do not want that.
That part is done. Once the letter count is inserted into the object, the count can begin. The full for loop is now
for(let x = 0; x < letters.length; x++){
if(obj.hasOwnProperty(letters[x]) === false){
obj[letters[x]] = 0
}
obj[letters[x]] += 1
}.
From this for loop, we can see that if this letter key does not exist, then set that key to zero, then begin the count. If the letter reappears, increase the count to 2, 3, and so on.
function countLetters(word){
const letters = word.split('')
const obj = {}
// obj['p'] += 1
for(let x = 0; x < letters.length; x++){
if(obj.hasOwnProperty(letters[x]) === false){
obj[letters[x]] = 0
}
obj[letters[x]] += 1
}
return obj
}const word = 'pneumonoultramicroscopicsilicovolcanoconiosis'
console.log(countLetters(word))
The full answer is
{
p: 2,
n: 4,
e: 1,
u: 2,
m: 2,
o: 9,
l: 3,
t: 1,
r: 2,
a: 2,
i: 6,
c: 6,
s: 4,
v: 1
}.
If you know of a better way, let me know.