Loop through an index of an array to search for a certain letter in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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

The function should return true if the character specified by second argument exists in any of the strings of the array, false otherwise.

Example

The code for this will be −

const arr = ['first', 'second', 'third', 'last'];
const searchForLetter = (arr = [], letter = '') => {
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(!el.includes(letter)){
         continue;
      };
      return true;
   };
   return false;
};
console.log(searchForLetter(arr, 's'));
console.log(searchForLetter(arr, 'x'));

Output

And the output in the console will be −

true
false
raja
Published on 20-Nov-2020 13:41:47
Advertisements