java script interview question challenge day 1.
Sanjeev Kumar
Senior Developer | Backend Development Specialist in Node.js & MongoDB | Angular Expertise for Dynamic Frontend Solutions | AWS
Problem: Create a JavaScript function to count how many times a specific character appears in a given string. You must achieve this without using built-in methods like split() or match().
SOLUTION
- We create an empty object charCount to store the count of each character.
- We iterate through each character in the string.
- For each character, we check if it already exists as a key in charCount. If it does, we increment its corresponding value by 1. If not, we initialize its value to 1.
- Finally, we return the count of the target character from the charCount object. If the character doesn't exist in the string, we return 0.
This approach effectively uses the object as a hash map to count occurrences, providing a solution to the problem.
function countOccurrences(str, char) {
const charMap = {};
for (let i = 0; i < str.length; i++) {
const currentChar = str[i];
charMap[currentChar] = (charMap[currentChar] || 0) + 1;
}
return charMap[char] || 0;
}
const myString = "hello world";
const charToCount = "l";
console.log(countOccurrences(myString, charToCount));
#JavaScript #StringManipulation #Hashmap #CountOccurrences #Algorithm #ProgrammingQuestion #CodingInterview #DataStructures
Frontend Developer
1 å¹´Angular developer
1 å¹´let abc = "hello world"; let x = 'o'; let y = 0; for (i = 0; i < abc.length; i++) { ?if (abc[i] === x) { ??y++ ?} } console.log(y)