最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove array elements with value of "" - Stack Overflow

programmeradmin8浏览0评论

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.

Share asked May 31, 2014 at 14:28 user3553493user3553493 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 15

Like 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

发布评论

评论列表(0)

  1. 暂无评论