Array filtering using first string letter in JavaScript

Suppose we have an array that contains name of some people like this:

const arr = ['Amy','Dolly','Jason','Madison','Patricia'];

We are required to write a JavaScript function that takes in one such string as the first argument, and two lowercase alphabet characters as second and third argument. Then, our function should filter the array to contain only those elements that start with the alphabets that fall within the range specified by the second and third argument.

Therefore, if the second and third argument are 'a' and 'j' respectively, then the output should be −

const output = ['Amy','Dolly','Jason'];


Let us write the code −

const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
const filterByAlphaRange = (arr = [], start = 'a', end = 'z') => {
   const isGreater = (c1, c2) => c1 >= c2;
   const isSmaller = (c1, c2) => c1 <= c2;
   const filtered = arr.filter(el => {
      const [firstChar] = el.toLowerCase();
      return isGreater(firstChar, start) && isSmaller(firstChar, end);
   return filtered;
console.log(filterByAlphaRange(arr, 'a', 'j'));


And the output in the console will be −

[ 'Amy', 'Dolly', 'Jason' ]

Updated on: 20-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started