Remove empty elements from an array in Javascript

2018-12-31 03:20发布

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?

30条回答
像晚风撩人
2楼-- · 2018-12-31 03:52

Just ES6 and newer versions method, assume array is below:

 const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];

Simple way:

 const clearArray = arr.filter( i => i );
查看更多
明月照影归
3楼-- · 2018-12-31 03:52

ES6: let newArr = arr.filter(e => e);

查看更多
荒废的爱情
4楼-- · 2018-12-31 03:53

What about this(ES6) : To remove Falsy value from an array.

var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];

arr.filter((v) => (!!(v)==true));

//output:

//[1, 2, "test", "false", true, 3, 4, 5, "end"]
查看更多
刘海飞了
5楼-- · 2018-12-31 03:54

Simply one liner:

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

or using underscorejs.org:

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
查看更多
孤独总比滥情好
6楼-- · 2018-12-31 03:56

The clean way to do it.

var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]
查看更多
人气声优
7楼-- · 2018-12-31 03:56

@Alnitak

Actually Array.filter works on all browsers if you add some extra code. See below.

var array = ["","one",0,"",null,0,1,2,4,"two"];

function isempty(x){
if(x!=="")
    return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]  

This is the code you need to add for IE, but filter and Functional programmingis worth is imo.

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
查看更多
登录 后发表回答