javascript array remove empty strings 1

javascript array remove empty strings

// an empty space between two commas in an array is categorized as a null value
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
// copy the following code snippet and use it anywhere in your own code
var filtered = array.filter(function (el) {
  return el != null;
});

console.log(filtered);

Here is what the above code is Doing:
1. We create an array with a bunch of null values in it.
2. We create a variable called filtered and assign it the return value of calling the filter method on the array.
3. The filter method takes a callback as an argument. The callback is a function that is invoked for each element in the array.
4. The callback function takes an argument called el. This argument represents each element in the array.
5. The callback function returns the element if the element is not equal to null.
6. The filter method returns a new array with all the elements that return true for the callback function.
7. The filtered variable is assigned the new array.
8. We log the filtered variable to the console.

Similar Posts