Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Array filtering using first string letter in JavaScript
Suppose we have an array that contains names of some people like this:
const arr = ['Amy','Dolly','Jason','Madison','Patricia']; console.log(arr);
[ 'Amy', 'Dolly', 'Jason', 'Madison', 'Patricia' ]
We are required to write a JavaScript function that takes in one such array as the first argument, and two lowercase alphabet characters as second and third arguments. Then, our function should filter the array to contain only those elements that start with alphabets that fall within the range specified by the second and third arguments.
Therefore, if the second and third arguments are 'a' and 'j' respectively, then the output should be:
['Amy','Dolly','Jason']
Using Array.filter() Method
We can use the Array.filter() method along with string comparison to filter names based on their first letter:
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'));
[ 'Amy', 'Dolly', 'Jason' ]
How It Works
The function works by:
- Converting each name's first character to lowercase using
el.toLowerCase()[0] - Using destructuring assignment
[firstChar]to extract the first character - Comparing the first character with the start and end range using
>=and<=operators - Returning only names whose first letter falls within the specified alphabetical range
Alternative Approach
Here's a more concise version of the same functionality:
const arr = ['Amy','Dolly','Jason','Madison','Patricia'];
const filterByRange = (names, start, end) => {
return names.filter(name => {
const firstLetter = name.toLowerCase()[0];
return firstLetter >= start && firstLetter <= end;
});
};
console.log(filterByRange(arr, 'a', 'j'));
console.log(filterByRange(arr, 'm', 'z'));
[ 'Amy', 'Dolly', 'Jason' ] [ 'Madison', 'Patricia' ]
Conclusion
Array filtering by first letter range is efficiently achieved using Array.filter() with string comparison. This technique is useful for alphabetical sorting and search functionalities.
