Finding word starting with specific letter in JavaScript


We are required to write a JavaScript function that takes in an array of string literals as the first argument and a single string character as the second argument.

Then our function should find and return the first array entry that starts with the character specified by the second argument.

Example

The code for this will be −

const names = ['Naman', 'Kartik', 'Anmol', 'Rajat', 'Keshav', 'Harsh', 'Suresh', 'Rahul'];
const firstIndexOf = (arr = [], char = '') => {
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el.substring(0, 1) === char){
         return i;
      };
   };
   return -1;
};
console.log(firstIndexOf(names, 'K'));
console.log(firstIndexOf(names, 'R'));
console.log(firstIndexOf(names, 'J'));

Output

And the output in the console will be −

1
3
-1

Updated on: 21-Nov-2020

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements