1. /**
  2. * Groups an array of strings into objects based on their first character.
  3. * @param {string[]} strings - The array of strings to group.
  4. * @returns {object} - An object where keys are the first characters of the strings,
  5. * and values are arrays of strings starting with that character.
  6. */
  7. function groupStrings(strings) {
  8. const grouped = {}; // Initialize an empty object to store the grouped strings.
  9. for (const str of strings) {
  10. if (str) { // Check if the string is not empty
  11. const firstChar = str[0]; // Get the first character of the string.
  12. if (grouped[firstChar]) {
  13. grouped[firstChar].push(str); // Add the string to the existing array for that character.
  14. } else {
  15. grouped[firstChar] = [str]; // Create a new array with the string for the character.
  16. }
  17. }
  18. }
  19. return grouped; // Return the grouped object.
  20. }

Add your comment