
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find 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
Advertisements