Computer >> Computer tutorials >  >> Programming >> Javascript

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 ]