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

是否有一种简单的方法,或者我需要循环并手动删除它们?


当前回答

如果需要删除所有空值(“”、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, " "]

其他回答

要移除孔,应使用

arr.filter(() => true)
arr.flat(0) // New in ES2019

对于删除孔、空和未定义:

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

用于删除hole和falsy(null,undefined,0,-0,0n,NaN,“”,false,document.all)值:

arr.filter(x => x)

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

注:

孔是一些没有元素的数组索引。

arr = [, ,];
console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole
arr[42] = 42;
console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole

arr1 = [1, 2, 3];
arr1[0] = (void 0);
console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole

arr2 = [1, 2, 3];
delete arr2[0]; // NEVER do this please
console.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole

上述所有方法都返回给定数组的副本,而不是就地修改它。

arr = [1, 3, null, 4];
filtered = arr.filter(x => x != null);
console.log(filtered); // [1, 3, 4]
console.log(arr); // [1, 3, null, 4]; not modified

删除空元素的最佳方法是使用Array.prototype.filter(),正如其他答案中已经提到的那样。

不幸的是,IE<9不支持Array.prototype.filter()。如果您仍然需要支持IE8或更旧版本的IE,可以使用以下polyfill在这些浏览器中添加对Array.protocol.filter()的支持:

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';
    if (this === void 0 || this === null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }
    return res;
  };
}

如果有人想要清理整个阵列或对象,这可能会有所帮助。

var qwerty = {
    test1: null,
    test2: 'somestring',
    test3: 3,
    test4: {},
    test5: {
        foo: "bar"
    },
    test6: "",
    test7: undefined,
    test8: " ",
    test9: true,
    test10: [],
    test11: ["77","88"],
    test12: {
        foo: "foo",
        bar: {
            foo: "q",
            bar: {
                foo:4,
                bar:{}
            }
        },
        bob: {}
    }
}

var asdfg = [,,"", " ", "yyyy", 78, null, undefined,true, {}, {x:6}, [], [2,3,5]];

function clean_data(obj) {
    for (var key in obj) {
        // Delete null, undefined, "", " "
        if (obj[key] === null || obj[key] === undefined || obj[key] === "" || obj[key] === " ") {
            delete obj[key];
        }
        // Delete empty object
        // Note : typeof Array is also object
        if (typeof obj[key] === 'object' && Object.keys(obj[key]).length <= 0) {
            delete obj[key];
        }
        // If non empty object call function again
        if(typeof obj[key] === 'object'){
            clean_data(obj[key]);
        }
    }
    return obj;
}

var objData = clean_data(qwerty);
console.log(objData);
var arrayData = clean_data(asdfg);
console.log(arrayData);

输出:

删除任何null、undefined、“”、“”空对象或空数组

jsfiddle在这里

这可能会帮助您:https://lodash.com/docs/4.17.4#remove

var details = [
            {
                reference: 'ref-1',
                description: 'desc-1',
                price: 1
            }, {
                reference: '',
                description: '',
                price: ''
            }, {
                reference: 'ref-2',
                description: 'desc-2',
                price: 200
            }, {
                reference: 'ref-3',
                description: 'desc-3',
                price: 3
            }, {
                reference: '',
                description: '',
                price: ''
            }
        ];

        scope.removeEmptyDetails(details);
        expect(details.length).toEqual(3);

scope.removeEmptyDetails = function(details){
            _.remove(details, function(detail){
                return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
            });
        };

我需要完成同样的任务,并遇到了这个线程。我最终使用数组“join”使用“_”分隔符创建字符串,然后使用正则表达式:-

1. replace "__" or more with just one "_",
2. replace preceding "_" with nothing "" and similarly 
3. replace and ending "_" with nothing ""

…然后使用数组“拆分”生成一个已清理的数组:-

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
var myStr = "";

myStr = myArr.join("_");

myStr = myStr.replace(new RegExp(/__*/g),"_");
myStr = myStr.replace(new RegExp(/^_/i),"");
myStr = myStr.replace(new RegExp(/_$/i),"");
myArr = myStr.split("_");

alert("myArr=" + myArr.join(","));

…或1行代码:-

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");

myArr = myArr.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");

alert("myArr=" + myArr.join(","));

…或,扩展Array对象:-

Array.prototype.clean = function() {
  return this.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
};

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");

alert("myArr=" + myArr.clean().join(","));