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

Removing all the empty indices from array in 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 inplace.

We are only required to remove the undefined and empty values and not all the falsy values.

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

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

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