Complete the code to check if a word starts with the given prefix.
function startsWith(word, prefix) {
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, prefix) {
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 words.
Fix the error in the code to correctly count words with the prefix.
function countWords(words, prefix) {
return words.filter(word => word.[1](prefix)).length;
}The filter method keeps words starting with the prefix using startsWith, then counts them.
Fill both blanks to create a function that returns a list of words starting with the prefix.
function filterWords(words, prefix) {
return words.[1](word => word.[2](prefix));
}filter selects words where startsWith returns true for the prefix.
Fill all three blanks to create a function that returns the count of words starting with the prefix using reduce.
function countWordsReduce(words, prefix) {
return words.reduce((count, word) => {
return count + (word.[1](prefix) ? [2] : [3]);
}, 0);
}The reduce method adds 1 to count if the word starts with prefix, else adds 0.