Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

remove falsy value javascript

let myArray = ['apple', 'orange', 'pair', , 'peach', , undefined, false];

// 1 - Remove all
console.log(myArray.filter(Boolean));
// ["apple","orange","pair","peach"]
console.log(myArray.filter(n => n));
// ["apple","orange","pair","peach"]

// 2 - Remove only empty slots (blank values)
console.log(myArray.filter(String));
/* ["apple","orange","pair","peach",undefined,false]
- if the array is composed by strings only
*/
console.log(myArray.flat());
/* ["apple","orange","pair","peach",undefined,false]
- not recommended as it can inadvertently flatten multi-dimensional arrays
*/
 
PREVIOUS NEXT
Tagged: #remove #falsy #javascript
ADD COMMENT
Topic
Name
2+1 =