admin管理员组文章数量:1328558
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
本文标签: javascriptRemove array elements with value of quotquotStack Overflow
版权声明:本文标题:javascript - Remove array elements with value of "" - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742260681a2442455.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论