Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
Can I change the type of the accumulator on the .reduce method?

I'm currently trying to reduce a string into number[], but I'm new to typescript and simply couldn't figure out how to type my code so that the typescript compiler would stop complaining...

What I'm trying to do:

matString.split(/[\n ]/).reduce((acc, cur, index) => acc[index] = Number(cur));

So far, I have tried typing it like this, but it just won't work :(

matString.split(/[\n ]/).reduce((acc: Array<number>, cur, index) => acc[index] = Number(cur)) as Array<number>;

Just for context, this code is receiving a matrix in the format of a string and I want to convert it down to an array so that I can work with it. I have already encountered this issue under different circumstances and had to work around it, but this time I would like to understand how to fix it.

Also, if it does help explain my issue better, here's a picture of my code followed by the compiler's error: code image with error

This is part of my solution to this exercise on exercism.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

While it's possible, it'd be far easier to avoid .reduce and just map the split string to Number, no explicit typing necessary:

const result = matString
  .split(/[\n ]/)
  .map(Number);

If you had to go the .reduce route, use generics to indicate the accumulator type, and remember to return the accumulator at the end of the callback:

const result = matString.split(/[\n ]/).reduce<Array<number>>((acc, cur, index) => {
    acc[index] = Number(cur);
    return acc;
}, []);

If the input is composed of a string that contains numeric characters, it might be better to match those characters, instead of splitting on newlines and spaces:

const result = matString
  .match(/\d+(?:\.\d+)?/g) // assuming there will always be at least one match
  .map(Number);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda