Search This Blog

2026/08/10

Javascript:Filter using flatMap



In  given array filter positive numbers.

Code :
const arr = [5, -2, 7, -1, 9];
const nonNegative = arr.flatMap((item)=>{
    return (item>0)?[item]:[]
})

//using filter only
//const nonNegative = arr.filter((item)=>item > 0)

console.log(nonNegative)

Output:
[ 5, 7, 9 ]


No comments:

Post a Comment