filter nullish elements with flatMap.javascript
Yes! flatMap can be used to filter out null or undefined elements implicitly when mapping over an array.
✅ How flatMap Works
flatMapapplies a function to each element and flattens the result.- If the function returns
nullorundefined, they automatically get filtered out.
Example: Filtering null or undefined elements with flatMap
const results = [
{ id: 1, value: "A" },
null,
{ id: 2, value: "B" },
undefined,
{ id: 3, value: "C" },
];
// Using `flatMap`
const filteredResults = results.flatMap(item => (item ? [item] : []));
console.log(filteredResults);
// Output: [ { id: 1, value: "A" }, { id: 2, value: "B" }, { id: 3, value: "C" } ]
🔹 This removes null and undefined without needing .filter(Boolean).
Use Case: Filtering null Prisma findMany Results
When fetching data from Prisma, you can use flatMap to filter out invalid values:
const results = await prisma.example.findMany();
// Using `flatMap` to remove `null` or `undefined`
const filteredResults = results.flatMap(item => item ? [item] : []);
console.log(filteredResults);
💡 Equivalent to: results.filter(Boolean), but more compact!
Use Case: Filtering While Mapping
If each element in results needs transformation, flatMap helps in both mapping and filtering in one step:
const results = await prisma.example.findMany();
// Transform & filter in one go
const transformedResults = results.flatMap(item =>
item ? { id: item.id, name: item.name.toUpperCase() } : []
);
console.log(transformedResults);
Best Practice
- Use
flatMapif you need both transformation and filtering. - If you only want to filter out
nullishvalues,.filter(Boolean)is simpler.
Let me know if you need further clarification! 🚀