Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!