Remove '0','undefined' and empty values from an array in JavaScript



To remove β€˜0’. β€˜undefined’ and empty values, you need to use the concept of splice(). Let’s say the following is our array βˆ’

var allValues = [10, false,100,150 ,'', undefined, 450,null]

Following is the complete code using for loop and splice() βˆ’

Example

var allValues = [10, false,100,150 ,'', undefined, 450,null]
console.log("Actual Array=");
console.log(allValues);
for (var index = 0; index < allValues.length; index++) {
   if (!allValues[index]) {
      allValues.splice(index, 1);
      index--;
   }
}
console.log("After removing false,undefined,null or ''..etc=");
console.log(allValues);

To run the above program, you need to use the following command βˆ’

node fileName.js.

Here, my file name is demo88.js.

Output

This will produce the following output βˆ’

PS C:\Users\Amit\JavaScript-code> node demo88.js
Actual Array=
[ 10, false, 100, 150, '', undefined, 450, null ]
After removing false,undefined,null or ''..etc=
[ 10, 100, 150, 450 ]
Updated on: 2020-09-07T08:21:15+05:30

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements