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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
raja
Published on 18-Sep-2020 16:59:52
Advertisements