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
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()
:
Also, here is some resources on Array.includes()
:
You can ask any clarifying questions, and I will try to answer them!
share
Your Answer
asked | |
viewed | 12 |
Related
- 2JavaScript: How to shift characters in a string to the left or right?
- 6how to check if object is empty or not.
- 1how to correctly cut the text in javascript?
- 2how to check is array symmetrical or not?
- 2How to selects all elements in a document | CSS
- 9How do you reverse a string in JavaScript?
- 1How to break Array.forEach iteration?
- 1Javascript function expressions vs. function declarations
- 1How to stop setInterval call with JavaScript?
- 1How to add a key/value pair to an object JavaScript?
- 1How do JavaScript closures work?