I have this array:
var x = ["happy", "", "sad", ""];
How do I convert it to:
["happy","sad"];
Similarly, how do I convert this array:
var y = ["happy", ""];
to:
["happy"];
I appreciate your help.
I have this array:
var x = ["happy", "", "sad", ""];
How do I convert it to:
["happy","sad"];
Similarly, how do I convert this array:
var y = ["happy", ""];
to:
["happy"];
I appreciate your help.
-
In addition to the answers, you could also use
array = array.filter(String)
- it should filter out empty strings – Ian Commented Aug 26, 2014 at 15:34
3 Answers
Reset to default 15Like this:
var x = ["happy", "", "sad", ""];
x = x.filter(function(v){
return v !== "";
});
You can also do return v;
but that would also filter out false
, null
, 0
, NaN
or anything falsy apart from ""
.
The above filters out all ""
from your array leaving only "happy"
and "sad"
.
Update: String method returns the argument passed to it in it's String representation. So it will return ""
for ""
, which is falsey. SO you can just do
x = x.filter(String);
Use Array.prototype.filter
array = array.filter(function (elem) { return elem; });
You could also do elem !== ""
if you don't want to filter out false
, null
, etc.
For your array you can use simple:
x = x.filter(Boolean);
This would filter also null
, undefined
, false
, 0
values