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