'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?



Solution 1:[1]

(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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder