To remove undefined values from an array using JavaScript, one of the easiest ways to do this is to use a for loop with an if conditional statement. Here is a simple function we will create to remove undefined values from an array.

function removeUndefinedValues(arr){
  var new_array = [];
  for (var i=0; i

In the function above, we simply create a new array, loop through all the values of the old array, and only add values that are not undefined to the new array.

Notice above we also make use of the push() method. This simply adds the element to the end of the array.

And here is our function in use with an example array.


var array_of_strings = ["This",undefined,"is","an","array",undefined,"with","undefined",undefined,"values","."]

function removeUndefinedValues(arr){
  var new_array = [];
  for (var i=0; i

When working with arrays of strings, it can be valuable to be able to easily filter and remove unwanted values from your array.

One such situation where you may want to remove values from an array is if you have a lot of undefined values in your array.

We can easily remove all undefined values from an array using JavaScript by simply iterating over the array and removing the undefined values. This is done simply with the use of a for loop and an if conditional statement.

Below again is the code for our function which will remove all instances of undefined values from an array in JavaScript.

function removeUndefinedValues(arr){
  var new_array = [];
  for (var i=0; i

Remove Undefined Values From an Array in JavaScript With the Filter Method

Below shows another way we can remove undefined values from an array, this time by using the filter() method.

var array_of_strings = ["This",undefined,"is","an","array",undefined,"with","undefined",undefined,"values","."]

var filtered_array = array_of_strings.filter(x => x != undefined);

Let's put this code in a function to make it easier to remove undefined values from an array.

function removeUndefinedValues(arr){
  return arr.filter(x => x != undefined);
};

And now let's give it the same example as we did to our first function above.

function removeUndefinedValues(arr){
  return arr.filter(x => x != undefined);
};

var array_of_strings = ["This",undefined,"is","an","array",undefined,"with","undefined",undefined,"values","."];

console.log(removeUndefinedValues(array_of_strings));

#Output:
['This', 'is', 'an', 'array', 'with', 'undefined', 'values', '.']

Hopefully this article has been useful for you to learn how to remove undefined values from an array in JavaScript.

Categorized in:

JavaScript,

Last Update: March 12, 2024