Group with reduce<Type>
Write a TypeScript function that uses reduce
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
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
Duplicate words
Empty array
Group by first letter
Single word
Different first letters
Algorithm Flow

Solution Approach
Best Answers
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;
}, {});
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
