Array filtering using first string letter in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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'];

Example

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'));

Output

And the output in the console will be −

[ 'Amy', 'Dolly', 'Jason' ]
raja
Published on 20-Nov-2020 09:38:55
Advertisements