Skip to content
Advertisement

How to proper use reduce() javascript/typescript

  1. I try to solve task below with reduce() and actually the result is ok. But I don’t know how to use acc in reduce() instead of acc1 or indexMax.
  2. How to apply typescript to this task.

The task: Find first word with max repeated letter count. For example rrrtygggg and ttbvfddjklyyyaseqq – the winner is rrrtygggg. If sequence has no repeated letters return ‘false’. Count only letters, ignor digits and special chars.

Here is my solution. Also I need to keep time complexity not higher than n. The most important part for me is reduce() and acc.

JavaScript

Advertisement

Answer

Iterate over the original words, with two outer variables:

  • One with a count of the maximum number of repeated letters found so far (starts at 0), and
  • The string corresponding to the count found above

All you need is a simple loop – on each iteration, calculate the repeat count for the current word being iterated over, and if it’s higher than the record so far, reassign the two outer variables.

JavaScript

To turn it into TypeScript, just add : string to the parameter types and : Record<string, number> to the repeatCounts object.

This would be possible to do with .reduce if the accumulator was an object with two properties, maxRepeatsFoundSoFar and bestWordSoFar instead of outer variables – but the typing and syntax noise would be annoying, outer variables are easier.

Advertisement