"Write a JavaScript function to get the number of occurrences of each letter in specified string." I've tried this way, but all my outputs are 0 and I really don't get why.
My idea was: Alphabetic order - so if one letter is the same with the next one, the counter increases. When it isn't the same, it logs the letter, how many times it appears and it resets the counter.
By the way, I don't know how to make it read the letters which appear only once. Can you help?
function count(string) {
let string1 = string.split("").sort().join("");
let counter = 0;
for (let i = 0; i < string.length; i++) {
if (string1[i] == string[i + 1]) {
counter++;
} else {
console.log(string1[i] + " " + counter);
counter = 0;
}
}
}
count("thequickbrownfoxjumpsoverthelazydog");
"Write a JavaScript function to get the number of occurrences of each letter in specified string." I've tried this way, but all my outputs are 0 and I really don't get why.
My idea was: Alphabetic order - so if one letter is the same with the next one, the counter increases. When it isn't the same, it logs the letter, how many times it appears and it resets the counter.
By the way, I don't know how to make it read the letters which appear only once. Can you help?
function count(string) {
let string1 = string.split("").sort().join("");
let counter = 0;
for (let i = 0; i < string.length; i++) {
if (string1[i] == string[i + 1]) {
counter++;
} else {
console.log(string1[i] + " " + counter);
counter = 0;
}
}
}
count("thequickbrownfoxjumpsoverthelazydog");
Share
Improve this question
edited Feb 28, 2018 at 18:00
Phiter
15k14 gold badges51 silver badges86 bronze badges
asked Feb 28, 2018 at 17:59
f0rtaf0rta
193 silver badges8 bronze badges
8
-
1
(string1[i] === string1[i + 1])
should work – TheChetan Commented Feb 28, 2018 at 18:03 - It was very smart splitting and sorting alphabetically. The previous ment points the main mistatke in your code. But about counting letters that appear only once, it'll not work if you use this approach of checking if the next letter is the same. – Phiter Commented Feb 28, 2018 at 18:05
- 2 Ask yourself: how would I do that in the real life? Picture a very long row of cards, with a letter written on each card. How would you count how many A's are there? How many B's? All at once? – georg Commented Feb 28, 2018 at 18:14
- @georg are u a teacher in real life? :-) – Ele Commented Feb 28, 2018 at 18:16
- 1 @Ele: sometimes ;) – georg Commented Feb 28, 2018 at 18:19
6 Answers
Reset to default 2Two minor errors in your code.
- Matching condition should be
string1[i] == string1[i + 1]
- Initiate counters with value 1 as each value will occur atleast one time.
function count(string) {
let string1 = string.split("").sort().join("");
let counter = 1;
for (let i = 0; i < string.length; i++) {
if (string1[i] == string1[i + 1]) {
counter++;
} else {
console.log(string1[i] + " " + counter);
counter = 1;
}
}
}
count("thequickbrownfoxjumpsoverthelazydog");
I would suggest you to use a different approach which will use .reduce
and will return a nice object of the counts.
function count(string) {
return string.split("").reduce(
(acc, el) => {
if(acc.hasOwnProperty(el))
acc[el]++;
else
acc[el] = 1;
return acc;
}, {}
)
}
var data = count("thequickbrownfoxjumpsoverthelazydog");
console.log(data);
Use the function reduce
to avoid the problem with only one occurence.
function count(string) {
return string.split("").reduce((a, letter) => {
a[letter] = (a[letter] || 0) + 1;
return a;
}, {});
}
console.log(count("thequickbrownfoxjumpsoverthelazydog"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Snippet with explanation
function count(string) {
return string.split("").reduce((a, letter) => {
var currentCount = a[letter];
if (currentCount) {
currentCount = currentCount + 1; // If previously counted + 1
} else {
currentCount = 1; // Else initialize with first occurence.
}
a[letter] = currentCount; //Store the new count.
return a;
}, {});
}
console.log(count("thequickbrownfoxjumpsoverthelazydog"));
Resource
Array.prototype.reduce()
Another approach I haven't seen here:
const count = (str) => {
let freq = {};
for(let i = 0; i < str.length; i++) { // you can use for...of instead!
const currentLetter = str.charAt(i);
freq[currentLetter] = freq[currentLetter] + 1 || 1;
}
return freq;
}
console.log(count("thequickbrownfoxjumpsoverthelazydog"));
- Create empty object
- Assign a letter as a key and add + 1 to value OR set value to 1 if key doesn't exist.
- Return the object.
You can do it like this
function count(text){
var i = 0;
var j = 0;
var chars = new Array();
var occurs = new Array();
for(i = 0;i < text.length;i++){
//save current char
chars.push(text[i]);
//get occurences
occurs.push(countOccurs(text, text[i]));
}
//clean for duplicates
for(i = 0;i < chars.length;i++){
for(j = (i + 1);j < chars.length;j++){
if(chars[i] == chars[j]){
chars[j] = "";
occurs[j] = 0;
}
}
}
//print it!
for(i = 0;i < chars.length;i++){
if(chars[i] != '')
console.log("The char " + chars[i] + " appears " + occurs[i] + " times.");
}
}
function countOccurs(text, character){
var i = 0;
var ret = 0;
for(i = 0;i < text.length;i++)
if(text[i] == character)
ret++
return ret;
}
count("abcdefabcd");
So you just count each char's occurs then clean the arrays.
const counterFunc = (string) => {
let counter = {};
string.split('').map((char) => {
if(typeof counter[char] !== 'undefined') {
counter = {
...counter,
[char]: counter[char] + 1
}
} else {
counter[char] = 1
}
})
return Object.keys(counter).map( k => {
return k + counter[k];
}).join('');
};
console.log(counterFunc("abcabcabcabcadftyeacrtfvcserfvaserdcvfrt"))
Hello People This is my first post in stack Over flow.
This is the Shortest Code that i can suggest.
function letterOccurence(string)
{
let countedString ={};
for(let letter of string)
{
countedString[letter] = (countedString[letter] || 0)+1; //This will count the occurrence of each letter
}
return countedString;
}
console.log(letterOccurence(("thequickbrownfoxjumpsoverthelazydog")));