find by first letter array

How to Find Elements Starting with a Specific Letter in an Array

As a programmer, you may often need to find elements in an array that start with a specific letter. There are several ways you can accomplish this in JavaScript.

Method 1: Using the filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. In this case, we can use it to filter out elements that don't start with the specified letter.


const arr = ["apple", "banana", "avocado", "orange", "kiwi"];
const letter = "a";
const filteredArr = arr.filter(element => element.charAt(0) === letter);
console.log(filteredArr); // Output: ["apple", "avocado"]
    

In the code above, we create an array called arr containing some fruits. We then define a variable letter and set it to "a". Finally, we use the filter() method to create a new array called filteredArr, which contains only elements that start with the letter "a".

Method 2: Using a for Loop

Another way to find elements starting with a specific letter is to use a for loop to iterate over the array and check each element.


const arr = ["apple", "banana", "avocado", "orange", "kiwi"];
const letter = "a";
const filteredArr = [];
for (let i = 0; i < arr.length; i++) {
  if (arr[i].charAt(0) === letter) {
    filteredArr.push(arr[i]);
  }
}
console.log(filteredArr); // Output: ["apple", "avocado"]
    

In this code, we define a new empty array called filteredArr. We then use a for loop to iterate over each element of the array. For each element, we check if the first letter matches the specified letter. If it does, we add it to the filteredArr array. Finally, we log the filteredArr array to the console.

Conclusion

Both the filter() method and a for loop can be used to find elements in an array that start with a specific letter. Which method you use depends on your personal preference and the specific requirements of your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe