admin管理员组

文章数量:1328760

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

本文标签: javascriptRemove array elements with value of quotquotStack Overflow