Complete the code to check if a word starts with the given prefix.
function startsWith(word: string, prefix: string): boolean {
return word.[1](prefix);
}The startsWith method checks if the string begins with the given prefix.
Complete the code to count how many words start with the prefix.
function countWords(words: string[], prefix: string): number {
let count = 0;
for (const word of words) {
if (word.[1](prefix)) {
count++;
}
}
return count;
}We use startsWith to check if each word begins with the prefix and count those that do.
Fix the error in the function to return the correct count of words starting with prefix.
function countWords(words: string[], prefix: string): number {
let count = 0;
for (const word of words) {
if (word.[1](prefix)) {
count += 1;
}
}
return count;
}The correct method to check if a word starts with a prefix is startsWith.
Fill both blanks to create a function that returns a list of words starting with the prefix.
function filterWords(words: string[], prefix: string): string[] {
return words.[1](word => word.[2](prefix));
}Use filter to select words, and startsWith to check the prefix.
Fill all three blanks to create a function that returns a dictionary with counts of words starting with each prefix in prefixes array.
function countWordsByPrefixes(words: string[], prefixes: string[]): {[key: string]: number} {
const result: {[key: string]: number} = {};
for (const prefix of prefixes) {
result[[1]] = words.filter(word => word.[2](prefix)).[3];
}
return result;
}We use the prefix as the key, filter words starting with it, and get the count using length.