Code Logo

Group with reduce<Type>

Published at25 Jul 2026
TypeScript Collections Medium 0 views
Like0

Write a TypeScript function that uses reduce with a generic type parameter to group words by their first letter into an object. The reduce() generic specifies the type of the accumulator, ensuring type safety throughout the reduction.

Array.reduce() is a generic method where U specifies the type of the accumulator. Without the type parameter, TypeScript infers the accumulator type from the initial value. With large or complex reductions, explicitly specifying the type helps the compiler and catches errors. The syntax is: arr.reduce(callback, initialValue).

The reduce function is one of the most powerful array methods. With proper typing, it can transform arrays into objects, Maps, Sets, or other arrays while maintaining type safety. The generic accumulator type U must match the type of the initial value and the return type of the callback.

Time complexity is O(n) where n is the array length. Space complexity is O(k) for the result object where k is the number of unique first letters.

Edge cases include empty arrays (returns initial value), arrays with words sharing the same first letter, case sensitivity, and ensuring the accumulator type annotation is correct.

Example Input & Output

Example 1
Input
["a","b","a"]
Output
{"a":["a","a"],"b":["b"]}
Explanation

Duplicate words

Example 2
Input
[]
Output
{}
Explanation

Empty array

Example 3
Input
["apple","banana","avocado","blueberry"]
Output
{"a":["apple","avocado"],"b":["banana","blueberry"]}
Explanation

Group by first letter

Example 4
Input
["test"]
Output
{"t":["test"]}
Explanation

Single word

Example 5
Input
["cat","dog"]
Output
{"c":["cat"],"d":["dog"]}
Explanation

Different first letters

Algorithm Flow

Recommendation Algorithm Flow for Group with reduce<Type>
Recommendation Algorithm Flow for Group with reduce<Type>

Solution Approach

function solution(words: string[]): any {
  return words.reduce<any>(function(acc: any, w: string) {
    var first = w.charAt(0);
    if (!acc[first]) acc[first] = [];
    acc[first].push(w);
    return acc;
  }, {});
}

Best Answers

typescript - Approach 1
function solution(words: string[]): any {
  return words.reduce<any>(function(acc: any, w: string) {
    var first = w.charAt(0);
    if (!acc[first]) acc[first] = [];
    acc[first].push(w);
    return acc;
  }, {});
}