I'm trying to solve a problem on a testing website and I'm getting confused on trying to find a way to match the letters of a passed in array wordlist.
In the below example it should be returning 2
, as ye
should be matched twice - in yesterday
and yellow
.
Without using a RegEx what would be the best way be to go about getting a passed in wordlist to return a number amount based on the 2nd argument input?
This is the code I have so far, that isn't working:
let wordList = ['yesterday', 'develop', 'environment', 'yellow', 'yikes', 'envious']
const countingLetters = (words, inputStart) => {
let total = 0;
for (let i = 0; i < words.length; i ) {
if (inputStart == words[i]) {
total = 1;
}
}
return total;
};
console.log(countingLetters(wordList, 'ye'));
CodePudding user response:
To do what you require without a regex, you can use the filter()
function, to search the array by a given condition, and the indexOf()
method to ensure that the match is at the start of the string:
let wordList = ['yesterday', 'develop', 'environment', 'yellow', 'yikes', 'envious']
const countingLetters = (words, inputStart) =>
words.filter(word => word.indexOf(inputStart) === 0).length;
console.log(countingLetters(wordList, 'ye'));