How to remove blank (undefined) elements from JavaScript array - JavaScript


Suppose we have an array of literals like this −

const arr = [4, 6, , 45, 3, 345, , 56, 6];

We are required to write a JavaScript function that takes in one such array and remove all the undefined elements from the array in place. We are only required to remove the undefined and empty values and not all the falsy values.

Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place.

Example

Following is the code −

const arr = [4, 6, , 45, 3, 345, , 56, 6]
const eliminateUndefined = arr => {
   for(let i = 0; i < arr.length; ){
      if(typeof arr[i] !== 'undefined'){
         i++;
         continue;
      };
      arr.splice(i, 1);
   };
};
eliminateUndefined(arr);
console.log(arr);

Output

This will produce the following output in console −

[
   4,  6, 45, 3,
 345, 56,  6
]

Updated on: 18-Sep-2020

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements