1

I have the following component:

function Params(props) {

    const { Parameters } = useFetchParams();

    return (
        <div className='Params'>
            {
                Parameters && Parameters.map(parameter => {
                    const { Name, Value } = parameter;
                    if (Name.includes(props.filter)) {
                        return (
                            <div className='Param' key={Name}>
                                <p>{Name}</p>
                                <p>{Value}</p>
                            </div>
                        )
                    }
                })
            }
        </div>
    )
}

I want to only display "Parameters" that include the text I'm passing in from props. You can see I'm currently using an if statement for this, and it seems clunky. I'm wondering if it's possible to map and filter over this array at the same time.

I've tried sticking filter at the end of the map but it returns an error.

Thanks for looking

3
  • You don't really need extra loop for .filter() you may still use a single .map() that returns conditionally either your JSX or null/false/undefined that will get ignored on render Commented Aug 16, 2020 at 21:31
  • What error are you getting? and also have you tried console logging the value of props.filter? Commented Aug 16, 2020 at 21:35
  • @DonJuanEco as a side note, if you find you're both filtering and mapping an array, then you might want to use .reduce. It can do both of those at the same time. Commented Aug 16, 2020 at 23:43

1 Answer 1

3

Like @Yevgen Gorbunkov suggests, what you're doing is fine, filtering before mapping is actually not faster, although it is perhaps, more readable. But yes, it is possible to do that. Like this:

function Params(props) {

    const { Parameters } = useFetchParams();

    return (
        <div className='Params'>
            {
                Parameters && Parameters.filter(parameter => parameter.Name.includes(props.filter))
                  .map(parameter => {
                    const { Name, Value } = parameter;
                    return (
                        <div className='Param' key={Name}>
                            <p>{Name}</p>
                            <p>{Value}</p>
                        </div>
                    )
                })
            }
        </div>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.