// Function that groups words by their first letter
function groupByFirstLetter(words) {
const groups = {}; // Object used as a dictionary
for (const word of words) {
const firstLetter = word[0]; // Extract first letter
// If the key doesn't exist, create an empty array
if (!groups[firstLetter]) {
groups[firstLetter] = [];
}
// Add the word to the correct group
groups[firstLetter].push(word);
}
return groups;
}
// List of words to group
const words = [
"Python", "JavaScript", "C", "Java", "C#", "PHP",
"C++", "Pascal", "SQL", "Rust"
];
const groupedWords = groupByFirstLetter(words);
// Print each group
for (const letter in groupedWords) {
console.log(`${letter}: [${groupedWords[letter].join(", ")}]`);
}
// Print the entire object
console.log(groupedWords);
/*
run:
P: [Python, PHP, Pascal]
J: [JavaScript, Java]
C: [C, C#, C++]
S: [SQL]
R: [Rust]
{
P: [ 'Python', 'PHP', 'Pascal' ],
J: [ 'JavaScript', 'Java' ],
C: [ 'C', 'C#', 'C++' ],
S: [ 'SQL' ],
R: [ 'Rust' ]
}
*/