How to Delete Empty Array Elements in JavaScript?

Estimated read time 2 min read

In JavaScript, you can delete empty array elements using the delete keyword. However, it’s important to note that this will create a hole in the array where the deleted element used to be, and the array length won’t be updated to reflect the removal of the element. This means that you might end up with sparse arrays, which can cause unexpected behavior in some cases.

If you want to remove empty array elements and keep the array length intact, you can use the filter() method instead. Here’s an example:

const myArray = ["foo", "", "bar", "", "baz"];

// Remove empty elements using filter()
const filteredArray = myArray.filter(Boolean);

console.log(filteredArray); // Output: ["foo", "bar", "baz"]

In this example, we have an array myArray with five elements, two of which are empty strings. We then use the filter() method with the Boolean constructor as a callback function to remove the empty elements from the array. The Boolean constructor returns false for empty elements and true for non-empty elements, so the filter() method only keeps the non-empty elements in the resulting array.

The filteredArray variable contains the updated array with the empty elements removed, and the array length is updated accordingly. Finally, we log the updated array to the console to verify that the empty elements have been removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply