Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda