Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,560 questions

51,419 answers

573 users

How to group words by first letter in JavaScript

1 Answer

0 votes
// 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' ]
}

*/

 



answered 12 hours ago by avibootz
...