DEV Community

Shadab Ali
Shadab Ali

Posted on

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