PASSWORD RESET

Your destination for complete Tech news

How to remove empty elements from an array in Javascript?

370 0
< 1 min read

To remove empty elements from an array in JavaScript, you can use the filter() method, which creates a new array with all elements that pass the test implemented by the provided function.

Here’s an example of how you can use the filter() method to remove empty elements from an array:

let myArray = [1, 2, '', 4, null, 6, undefined, 8];
let filteredArray = myArray.filter(item => item);
console.log(filteredArray); // [1, 2, 4, 6, 8]

In this example, the filter() method calls the provided function for each element in the array and includes only the elements for which the function returns a truthy value. Empty values, such as an empty string, null, and undefined, are considered falsy values in JavaScript, so they are filtered out by the function.

You can also use the filter() method in combination with the typeof operator to remove specific types of elements from the array. For example, to remove all null and undefined values, you can use the following code:

let myArray = [1, 2, '', 4, null, 6, undefined, 8];
let filteredArray = myArray.filter(item => item !== null && typeof item !== 'undefined');
console.log(filteredArray); // [1, 2, '', 4, 6, 8]

Keep in mind that the filter() method does not modify the original array, but rather creates a new array with the filtered elements. If you want to modify the original array, you can use the splice() method in combination with a loop, as shown in the following example:

let myArray = [1, 2, '', 4, null, 6, undefined, 8];
for (let i = myArray.length - 1; i >= 0; i--) {
  if (!myArray[i]) {
    myArray.splice(i, 1);
  }
}
console.log(myArray); // [1, 2, 4, 6, 8]

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.