DEV Community

Shadab Ali
Shadab Ali

Posted on

1

Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.

OR

Q: Implement lodash compact function

INPUT:
const array=[1, null , 0 , 2 , 3 , 4 , 5 ," " , undefined , NaN];

OUTPUT : [1, 2, 3, 4, 5]

======================================

function compact(ar){
let newArr=[];
for(let i=0;i< ar.length;i++){
if(!(ar[i] === false || ar[i] === null || ar[i] === 0 || ar[i] === "" || ar[i] === undefined || (typeof ar[i] == 'number' && !ar[i]) ))
{
newArr.push(ar[i])
}
}
return newArr
}
Enter fullscreen mode Exit fullscreen mode

====================================

The best and easy approach in the comment

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay