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

95
Vistas
Triming within a filter method in React

I am trying to remove trailing spaces from a phrase as I am filtering my data but the trim() method doesn't seem to be removing the spaces as expected if I try and mutate the data within the filter method.

Here is my code:

{item.fields
       .filter(item =>item.text.trim() === description)
       .map((field, i) => {
       return (<div></div>)
})}

Any idea why the trim() method wouldn't work?

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

0

(I assume item in your filter callback should be field. Technically doesn't matter, but much easier to read.)

...if I try and mutate the data within the filter method...

The trim call works, but then you're not keeping the result for anything. You're not mutating the data. You only used it temporarily when doing the ===.

You could trim again in the map callback:

{item.fields
    .filter(field => field.text.trim() === description)
    .map((field, i) => {
        return <div>{field.text.trim()}</div>; // <===
    })
}

Or you could make your filter callback do double-duty, trimming the field and doing the comparison. Those kinds of side-effects in filter callbacks are often considered poor practice, though:

{item.fields
    .filter(field => {
        field.text = field.text(); // Side effect, often considered poor practice
        return field.text === description;
    })
    .map((field, i) => {
        return <div>{field.text}</div>;
    })
}

Or when you receive item.fields, you could trim them once so you don't have to do it on every render.

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