Remove empty elements from an array in Javascript

Ask a question+
0

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

add comment

1 Answer

1

If by empty you mean having a value of "" or NULL, then you could do something like this:

// Starting array
var exampleArray = ["Hello","","World","!","","This","","is","","an","","empty","","thing:",""];

// Removing all empty values
exampleArray = exampleArray.filter((value) => { return value != ""; })

So what this does is it goes through the array and only returns all the elements that do not have a value of "". If you wanted to have it see if it was one of different values equivalent to "", you could do something like this:

// Starting array
var exampleArray = [NaN,"Hello","","World","!",undefined,"This",null,"is","","an","","empty","","thing:",""];
var noValues = ["",null,undefined,NaN]; // You could add any values that you want to treat as "empty"

// Removing all empty values
exampleArray = exampleArray.filter((value) => { return !noValues.includes(value); })

Just to let you know, I have tested both of these and know that they work.

Here are two resources on Array.filter():

  1. MDN Web Docs
  2. W3Schools

Also, here is some resources on Array.includes():

  1. MDN Web Docs
  2. W3Schools

You can ask any clarifying questions, and I will try to answer them!

Batman 300

Thanks this worked for me.

Ashutosh200

Good! I’m glad it worked

Batman
add comment

Your Answer