从Javascript数组中删除空元素

如何从JavaScript中的数组中删除空元素?

有没有简单的方法,还是我需要遍历它并手动将其删除?

TonyMandy2020/03/10 00:52:50

Filtering out invalid entries with a regular expression

array = array.filter(/\w/);
filter + regexp
EvaPro2020/03/10 00:52:50
var data= { 
    myAction: function(array){
        return array.filter(function(el){
           return (el !== (undefined || null || ''));
        }).join(" ");
    }
}; 
var string = data.myAction(["I", "am","", "working", "", "on","", "nodejs", "" ]);
console.log(string);

Output:

I am working on nodejs

It will remove empty element from array and display other element.

Itachi神乐2020/03/10 00:52:50

When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.

var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});

Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.

Returns

["some string yay", "Other string yay"]
泡芙神无伽罗2020/03/10 00:52:50
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })

console.log(r) 

[1,2,3]

梅Harry米亚2020/03/10 00:52:50

You should use filter to get array without empty elements. Example on ES6

const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
Near泡芙2020/03/10 00:52:50

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"]
乐小小猪猪2020/03/10 00:52:50

与尝试像建议的那样通过循环和拼接相比,您可能会发现更容易遍历数组并从要保留在数组中的项目中构建新的数组,这是因为在循环时修改了数组的长度过度会带来问题。

您可以执行以下操作:

function removeFalsyElementsFromArray(someArray) {
    var newArray = [];
    for(var index = 0; index < someArray.length; index++) {
        if(someArray[index]) {
            newArray.push(someArray[index]);
        }
    }
    return newArray;
}

实际上,这是一个更通用的解决方案:

function removeElementsFromArray(someArray, filter) {
    var newArray = [];
    for(var index = 0; index < someArray.length; index++) {
        if(filter(someArray[index]) == false) {
            newArray.push(someArray[index]);
        }
    }
    return newArray;
}

// then provide one or more filter functions that will 
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
    return (item == null || typeof(item) == "undefined");
}

// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);

// results == [1,2,3,3,4,4,5,6]

You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)

宝儿小胖2020/03/10 00:52:50

如果使用库是一种选择,我知道underscore.js具有一个称为compact()的函数http://documentcloud.github.com/underscore/,它还具有其他一些与数组和集合有关的有用函数。

以下是他们的文档摘录:

_.compact(array)

返回删除了所有伪造值的数组的副本。在JavaScript中,false,null,0,“”,undefined和NaN都是虚假的。

_.compact([0,1,false,2,'',3]);

=> [1、2、3]

飞云斯丁GO2020/03/10 00:52:50
ES6: let newArr = arr.filter(e => e);
伽罗理查德2020/03/10 00:52:50

@Alnitak

如果您添加一些额外的代码,Array.filter实际上可以在所有浏览器上运行。见下文。

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"]  

这是您需要为IE添加的代码,但是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;
  };
}
神奇Tony古一2020/03/10 00:52:50

由于没有人提及它,并且大多数人的项目中都包含下划线,因此您也可以使用_.without(array, *values);

_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
阿良2020/03/10 00:52:50

只是ES6较新的版本方法,假设数组如下:

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

简单方法:

 const clearArray = arr.filter( i => i );
Near小哥西门2020/03/10 00:52:50

做到这一点的干净方法。

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"]
Stafan卡卡西2020/03/10 00:52:50

如果您拥有Javascript 1.6或更高版本,则可以使用Array.filter简单的return true回调函数来使用,例如:

arr = arr.filter(function() { return true; });

因为会.filter自动跳过原始数组中缺少的元素。

上面链接的MDN页面还包含一个不错的错误检查版本,filter版本可以在不支持正式版本的JavaScript解释器中使用。

请注意,这不会删除null条目,也不会删除具有显式undefined值的条目,但是OP特别要求“丢失”的条目。

达蒙逆天Pro2020/03/10 00:52:50

要去除孔,应使用

arr.filter(() => true)
arr.flat(0) // Currently stage 3, check compatibility before using this

为了消除空洞,以及虚假(空,未定义,0,-0,NaN,“”,false,document.all)值:

arr.filter(x => x)

要删除空,空和未定义的孔:

arr.filter(x => x != null)

arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
console.log(arr.filter(x => x)); // [42]
console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]

Stafan村村达蒙2020/03/10 00:52:50

如果您需要删除所有空值(“”,null,undefined和0):

arr = arr.filter(function(e){return e}); 

要删除空值和换行符:

arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});

例:

arr = ["hello",0,"",null,undefined,1,100," "]  
arr.filter(function(e){return e});

返回:

["hello", 1, 100, " "]

更新(基于Alnitak的评论)

在某些情况下,您可能希望在数组中保留“ 0”并删除其他任何内容(null,undefined和“”),这是一种方法:

arr.filter(function(e){ return e === 0 || e });

返回:

["hello", 0, 1, 100, " "]
小小乐2020/03/10 00:52:50

只需一根衬垫:

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

或使用underscorejs.org

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]