Categories
JavaScript Answers

How to do map and filter an array at the same time with JavaScript?

Spread the love

To map and filter an array at the same time with JavaScript, we use the flatMap method.

For instance, we write

const names = options.flatMap((o) => (o.assigned ? [o.name] : []));

to call options.flatMap with a callback that checks if o.assigned is set.

If it is, then we array with o.name inside.

Otherwise, we return an empty array.

And we use flatMap to combine them into one flattened array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.