How to get the indexes of words from an array of strings that start with a specific letter in TypeScript

1 Answer

0 votes
function getIndexesOfWordsStartingWith(array: string[], letter: string): number[] {
    const indexes: number[] = [];
    
    array.forEach((word, index) => {
        if (word.toLowerCase().startsWith(letter.toLowerCase())) {
            indexes.push(index);
        }
    });
    
    return indexes;
}

const stringArray: string[] = ["zero", "one", "two", "three", "four", "five", 
                               "six", "seven", "eight", "nine", "ten"];
const specificLetter: string = 't';

const indexes: number[] = getIndexesOfWordsStartingWith(stringArray, specificLetter);

console.log(indexes);


 
 
/*
run:
 
[2, 3, 10] 
 
*/

 



answered Mar 14, 2025 by avibootz
...