1const a = [3,,null, false, undefined, 1];
2
3// Remove falsey
4a.filter(Boolean);
5
6// Remove specific (undefined)
7a.filter(e => e !== undefined);
1var data = [42, 21, undefined, 50, 40, undefined, 9];
2
3data = data.filter(function( element ) {
4 return element !== undefined;
5});
1var colors=["red","blue",,null,undefined,,"green"];
2
3//remove null and undefined elements from colors
4var realColors = colors.filter(function (e) {return e != null;});
5console.log(realColors);
1var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
2
3var filtered = array.filter(function (el) {
4 return el != null;
5});
6
7console.log(filtered);
1//? to use Array.prototype.filter here might be obvious.
2//So to remove only undefined values we could call
3
4var data = [42, 21, undefined, 50, 40, undefined, 9];
5
6data = data.filter(function( element ) {
7 return element !== undefined;
8});
9
10//If we want to filter out all the falsy values (such as 0 or null),
11//we can use return !!element; instead. But we can do it slighty more elegant,
12//by just passing the Boolean constructor function,
13//respectively the Number constructor function to .filter:
14
15data = data.filter( Number );
16
17//That would do the job in this instance,
18//to generally remove any falsy value,
19//we would call
20data = data.filter( Boolean );
21//Since the Boolean() constructor returns true on truthy values
22//and false on any falsy value, this is a very neat option.