How to Remove Empty Elements from an Array in Javascript
JavaScript suggests several methods to remove elements from an Array. You can delete items from the end of an array using pop(), from the beginning using shift(), or from the middle using splice() functions. Let's discuss them.
pop()
The Array.prototype.pop() method removes the last element from an array and returns it.
shift()
The Array.prototype.shift() method removes the first element from an array and returns it.
The pop() and shift() methods change the length of the array.
You can use the push() to add an element to the end of an array or the unshift() method to add a new element to the beginning of an array.
splice()
The Array.prototype.splice() method mutates the array, removes the specified elements from it, and then returns these removed elements as a new array. The Array.prototype.splice() needs two or more arguments as input. The first argument defines the location at which to begin removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they define elements to replace the removed elements.
The code below removes one item at position 2:
If you don't know the index of the element you want to remove, the splice() can be coupled with indexOf() to find and remove the items you want. The indexOf() searches the array and finds the value you give it. The method will return the first index at which the specified element lies in the array, or -1 if it is not present:
filter()
The filter() method creates a new array, unlike splice(). The method does not modify the array on which it is invoked. Instead, it returns a brand new array. You should pass a function to this method, and it "filters" the items based on the result of the function:
The delete Operator
This operator will delete the element which you specify in the index (remember to start counting from zero).
The delete operator actually does not remove the index from the array. It just makes it null.