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
Grouping names based on first letter in JavaScript
Suppose, we have an array of names like this:
const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
We are required to write a JavaScript function that takes in one such array. The function should return an array of objects with two properties:
letter -> the letter on which the names are grouped
names -> an array of names that falls in that group
Example
The code for this will be:
const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
const groupNames = arr => {
const map = arr.reduce((acc, val) => {
let char = val.charAt(0).toUpperCase();
acc[char] = [].concat((acc[char] || []), val);
return acc;
}, {});
const res = Object.keys(map).map(el => ({
letter: el,
names: map[el]
}));
return res;
};
console.log(groupNames(arr));
Output
The output in the console:
[
{ letter: 'S', names: [ 'Simon', 'Susi' ] },
{ letter: 'M', names: [ 'Mike' ] },
{ letter: 'J', names: [ 'Jake', 'James' ] },
{ letter: 'L', names: [ 'Lara' ] },
{ letter: 'B', names: [ 'Blake' ] }
]
How It Works
The function uses reduce() to build an object where each key is the first letter and each value is an array of names starting with that letter. Then Object.keys() and map() transform this object into the desired array format.
Alternative Approach Using forEach
const arr = ["Simon", "Mike", "Jake", "Lara", "Susi", "Blake", "James"];
const groupNamesSimple = arr => {
const groups = {};
arr.forEach(name => {
const firstLetter = name.charAt(0).toUpperCase();
if (!groups[firstLetter]) {
groups[firstLetter] = [];
}
groups[firstLetter].push(name);
});
return Object.keys(groups).map(letter => ({
letter: letter,
names: groups[letter]
}));
};
console.log(groupNamesSimple(arr));
[
{ letter: 'S', names: [ 'Simon', 'Susi' ] },
{ letter: 'M', names: [ 'Mike' ] },
{ letter: 'J', names: [ 'Jake', 'James' ] },
{ letter: 'L', names: [ 'Lara' ] },
{ letter: 'B', names: [ 'Blake' ] }
]
Conclusion
Both approaches effectively group names by their first letter. The reduce() method is more functional, while forEach() is more straightforward and easier to understand.
