- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] } ]
Advertisements