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

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


试试这个。将数组传递给它,它将返回并删除空元素*更新以解决Jason指出的错误

function removeEmptyElem(ary) {
    for (var i = ary.length - 1; i >= 0; i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }       
    }
    return ary;
}

您可能会发现,循环遍历数组并使用要从数组中保留的项构建新数组比按照建议进行循环和拼接更容易,因为在循环遍历时修改数组的长度可能会带来问题。

你可以这样做:

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]

你明白了——你可以有其他类型的过滤函数。可能比你需要的更多,但我感觉很慷慨…;)


编辑:这个问题几乎在九年前就得到了回答,当时Array.prototype中没有太多有用的内置方法。

现在,当然,我建议您使用过滤方法。

请记住,此方法将返回一个新数组,其中包含传递给它的回调函数的条件的元素。

例如,如果要删除空值或未定义的值:

var array=[0,1,null,2,“”,3,undefined,3,,,,4,,,5,,6,,,];var filtered=array.filter(函数(el){返回el!=无效的});console.log(已过滤);

这取决于你认为什么是“空”的。例如,如果你处理字符串,上面的函数不会删除空字符串的元素。

我经常看到的一个典型模式是删除错误的元素,其中包括空字符串“”、0、NaN、null、undefined和false。

您可以传递给筛选方法、布尔构造函数或返回筛选条件函数中的相同元素,例如:

var filtered = array.filter(Boolean);

Or

var filtered = array.filter(function(el) { return el; });

在这两种情况下,这都是有效的,因为在第一种情况下过滤器方法将布尔构造函数作为函数调用,转换值,而在第二种情况下过滤方法在内部将回调的返回值隐式转换为布尔值。

如果您正在使用稀疏数组,并且正在尝试消除“空洞”,则可以使用filter方法传递返回true的回调,例如:

var spareArray=[0,,1,,,2,,3],cleanArray=sparseArray.filter(函数(){return true});console.log(cleanArray);//[ 0, 1, 2, 3 ]

老答案:不要这样做!

我使用这个方法,扩展了本机Array原型:

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);

或者您可以简单地将现有元素推入其他数组:

// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
  var newArray = new Array();
  for (var i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);

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

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

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

上面链接的MDN页面还包含一个很好的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。

注意,这不会删除空条目,也不会删除具有显式未定义值的条目,但OP特别请求“缺少”条目。


这是可行的,我在AppJet中测试了它(你可以复制粘贴代码到它的IDE上,然后按“reload”查看它的工作情况,不需要创建帐户)

/* appjet:version 0.1 */
function Joes_remove(someArray) {
    var newArray = [];
    var element;
    for( element in someArray){
        if(someArray[element]!=undefined ) {
            newArray.push(someArray[element]);
        }
    }
    return newArray;
}

var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/

@阿尔尼塔克

实际上,如果您添加一些额外的代码,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添加的代码,但过滤器和函数式编程是值得的。

//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;
  };
}

使用正则表达式筛选出无效条目

array = array.filter(/\w/);
filter + regexp

几个简单的方法:

var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];

arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Number) 
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Boolean) 
// [1, 2, 3, -3, 4, 4, 5, 6]

或-(仅适用于“text”类型的单个数组项)

['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); 
// output:  ["1","2","3","4","5"]

或-经典方式:简单迭代

var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
    len = arr.length, i;

for(i = 0; i < len; i++ )
    arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);  // cut the array and leave only the non-empty values
// [1,2,3,3,[],Object{},5,6]

jQuery:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
    
arr = $.grep(arr, n => n == 0 || n);
// [1, 2, 3, 3, 0, 4, 4, 5, 6]

那怎么办

js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6

干净的方法。

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

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

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

以下是他们文档的摘录:

_.compact(数组)返回删除了所有错误值的数组副本。在JavaScript中,false、null、0、“”、undefined和NaN都是假的。_.compact([0,1,false,2,'',3]);=> [1, 2, 3]


我需要完成同样的任务,并遇到了这个线程。我最终使用数组“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(","));

我只是在上面的“用全局构造函数调用ES5的数组..filter()”高尔夫技巧中添加了我的声音,但我建议使用Object而不是上面建议的String、Boolean或Number。

具体来说,ES5的filter()已经不会为数组中未定义的元素触发;因此,一个普遍返回true(返回所有元素filter()命中)的函数必然只返回未定义的元素:

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

然而,写出。。。(function(){return true;})的长度大于写入。。。(对象);在任何情况下,Object构造函数的返回值都将是某种类型的对象。与上面建议的基本装箱构造函数不同,没有可能的对象值是假的,因此在布尔设置中,object是function(){return true}的缩写。

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

带下划线/Loddash:

一般使用情况:

_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

有空:

_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]

无需参阅lodash文档。


只需一个衬垫:

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

另一种方法是利用数组的长度属性:将非空项打包到数组的“左侧”,然后减少长度。它是一种就地算法-不分配内存,对垃圾收集器来说太糟糕了-并且它具有非常好的最佳/平均/最坏情况行为。

与这里的其他解决方案相比,这个解决方案在Chrome上速度快2到50倍,在Firefox上速度快5到50倍http://jsperf.com/remove-null-items-from-array

下面的代码将不可枚举的“removeNull”方法添加到Array中,该方法为菊花链返回“this”:

var removeNull = function() {
    var nullCount = 0           ;
    var length    = this.length ;
    for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
    // no item is null
    if (!nullCount) { return this}
    // all items are null
    if (nullCount == length) { this.length = 0; return this }
    // mix of null // non-null
    var idest=0, isrc=length-1;
    length -= nullCount ;                
    while (true) {
         // find a non null (source) slot on the right
         while (!this[isrc])  { isrc--; nullCount--; } 
         if    (!nullCount) { break }       // break if found all null
         // find one null slot on the left (destination)
         while ( this[idest]) { idest++  }  
         // perform copy
         this[idest]=this[isrc];
         if (!(--nullCount)) {break}
         idest++;  isrc --; 
    }
    this.length=length; 
    return this;
};  

Object.defineProperty(Array.prototype, 'removeNull', 
                { value : removeNull, writable : true, configurable : true } ) ;

美好的很不错的我们也可以像这样替换所有数组值

Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
    for( var i = 0; i < this.length; i++ )  
    {
        if( this[i] == OldValue )       
        {
            this[i] = newValue;
        }
    }
};

foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(e => e === 0 ? true : e)

回报

[0, 1, 2, 3, "four"]

如果你确定你的数组中没有0,那么它看起来会更好一些:

foo.filter(e => e)

第一个例子是,当使用上面投票最高的答案时,我得到的字符串长度大于1的单个字符。下面是我解决这个问题的方法。

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

如果未定义,则不返回,如果长度大于0,则返回。希望这能帮助一些人。

退换商品

["some string yay", "Other string yay"]

这是另一种方法:

var arr = ["a", "b", undefined, undefined, "e", undefined, "g", undefined, "i", "", "k"]
var cleanArr = arr.join('.').split(/\.+/);

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

_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]

下面是一个使用变量行为和ES2015胖箭头表达式的示例:

Array.prototype.clean = function() {
  var args = [].slice.call(arguments);
  return this.filter(item => args.indexOf(item) === -1);
};

// Usage
var arr = ["", undefined, 3, "yes", undefined, undefined, ""];
arr.clean(undefined); // ["", 3, "yes", ""];
arr.clean(undefined, ""); // [3, "yes"];

这个呢(ES6):从数组中删除Falsy值。

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

删除空元素的最佳方法是使用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;
  };
}

“误用”。。。在(对象成员)循环中。=>循环体中仅显示真实值。

// --- Example ----------
var field = [];

field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------

var originalLength;

// Store the length of the array.
originalLength = field.length;

for (var i in field) {
  // Attach the truthy values upon the end of the array. 
  field.push(field[i]);
}

// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);

这样做怎么样

// Removes all falsy values 
arr = arr.filter(function(array_val) { // creates an anonymous filter func
    var x = Boolean(array_val); // checks if val is null
    return x == true; // returns val to array if not null
  });

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

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在这里


这只会删除空值,而不是虚假值,我认为这是更可取的。

也可以选择删除空值。

这种方法应该比使用拼接快得多。

    function cleanArray(a, removeNull) {
        var i, l, temp = [];
        l = a.length;
        if (removeNull) {
            for (i = 0; i < l; i++) {
                if (a[i] !== undefined && a[i] !== null) {
                    temp.push(a[i]);
                }
            }
        } else {
            for (i = 0; i < l; i++) {
                if (a[i] !== undefined) {
                    temp.push(a[i]);
                }
            }
        }
        a.length = 0;
        l = temp.length;
        for (i = 0; i < l; i++) {
            a[i] = temp[i];
        }
        temp.length = 0;
        return a;
    }
    var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ];
    cleanArray(myArray);
    myArray;

简单ES6

['a','b','',,,'w','b'].filter(v => v);

var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })

console.log(r) 

[1,2,3]


这可能会帮助您: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));
            });
        };

使用筛选器删除数组中的空字符串。

var s=['1201,karthikeyan,K201,直升机,karthikeyan.a@limitlessmobil.com,8248606269,7/14/201745680,TN-KAR24,88001000200300,Karthikeyan,2017年11月24日,Karthikey an,2017月11日,可用\r,'' ]var newArr=s.filter(函数(条目){return entry.trim()!=“”;})console.log(newArr);


您应该使用filter获取不含空元素的数组。ES6示例

const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);

要移除孔,应使用

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

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);

输出:

我正在研究nodejs

它将从数组中删除空元素并显示其他元素。


ES6:

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

实际上,您可以使用ES6+方法,假设数组如下:

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

答案可以是以下两种方式之一:

第一种方式:常量clearArray=arr.filter(i=>i);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]第二种方式:const clearArray=arr.filter(布尔值);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

2022年10月14日更新:

这两个答案并不完全正确,即使在给定的例子中,是的,它是有效的,但请注意给定数组中的数字0,通过这两种方式,数字0都会消失,这显然与使用布尔强制检查项目有关。

完全正确的方法是检查nulish并删除它们:

const notNil = (i) => !(typeof i === 'undefined' || i === null);

const clearArray = arr.filter(i => isNil(i));

常量arr=[1,2,3,未定义,4,5,6,未定义、7,8,未定义;未定义,0,9];常量notNil=(i)=>!(类型i===“未定义”||i===null);console.log(“非nil:”,arr.filter(非nil));


这是我清理空字段的解决方案。

从费用对象开始:仅获取可用属性(带贴图)筛选空字段(带筛选器)将结果解析为整数(带映射)

fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );

就地解决方案:

function pack(arr) { // remove undefined values
  let p = -1
  for (let i = 0, len = arr.length; i < len; i++) {
    if (arr[i] !== undefined) { if (p >= 0) { arr[p] = arr[i]; p++ } }
    else if (p < 0) p = i
  }
  if (p >= 0) arr.length = p
  return arr
}

let a = [1, 2, 3, undefined, undefined, 4, 5, undefined, null]
console.log(JSON.stringify(a))
pack(a)
console.log(JSON.stringify(a))

var a = [{a1: 1, children: [{a1: 2}, undefined, {a1: 3}]}, undefined, {a1: 5}, undefined, {a1: 6}]
function removeNilItemInArray(arr) {
    if (!arr || !arr.length) return;
    for (let i = 0; i < arr.length; i++) {
        if (!arr[i]) {
            arr.splice(i , 1);
            continue;
        }
        removeNilItemInArray(arr[i].children);
    }
}
var b = a;
removeNilItemInArray(a);
// Always keep this memory zone
console.log(b);

删除所有空元素

如果数组包含空对象、数组和字符串以及其他空元素,我们可以使用以下方法删除它们:

const arr=[[],['not','empty'],{},{key:'value'},0,1,null,2,“”,“here”,“”3,undefined,3,,,4,4,5,6,,]let filtered=JSON.stringify(arr.filter((obj)=>{回来[null,未定义,“”]。includes(obj)}).filter((el)=>{返回类型el!=“object”||对象.键(el).长度>0}))console.log(JSON.parse(已过滤))

简单压缩(从数组中删除空元素)

使用ES6:

常量arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]let filtered=arr.filter((obj)=>{return!〔null,undefined〕.includes(obj)})console.log(已过滤)

使用纯Javascript->

var arr=[0,1,null,2,“”,3,未定义,3,,,4,4,5,6,,]var filtered=arr.filter(函数(obj){return!〔null,undefined〕.includes(obj)})console.log(已过滤)


只需使用array.filter(字符串);它返回javascript中数组的所有非空元素


可以使用带有索引和in运算符的筛选器

设a=[1,,2,,,3];设b=a.filter((x,i)=>a中的i);console.log({a,b});


如果您使用的是NodeJS,则可以使用干净的深度包。使用npm我之前清洁过。

const cleanDeep = require('clean-deep');
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
const filterd = cleanDeep(array);
console.log(filterd);

要从数组中删除未定义的元素,只需使用

常量数组=[{name:“tim”,年龄:1},未定义,{姓名:“ewrfer”,年龄:22岁},{姓名:“3tf5gh”,年龄:56},无效的{姓名:“kygm”,年龄:19岁},未定义,];console.log(array.filter(布尔));


以上答案都不适用于所有类型。下面的解决方案将删除null、undefined、{}[]、NaN,并保留日期字符串,最好的是它甚至从嵌套对象中删除。

function removeNil(obj) {
    // recursively remove null and undefined from nested object too.
    return JSON.parse(JSON.stringify(obj), (k,v) => {
      if(v === null || v === '') return undefined;
      // convert date string to date.
      if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))
        return new Date(v);
      // remove empty array and object.
      if(typeof v === 'object' && !Object.keys(v).length) return undefined;
      return v;
    });
  }

函数removeNil(obj){//递归地从嵌套对象中删除null和undefined。返回JSON.parse(JSON.stringify(obj),(k,v)=>{如果(v===null||v==='')返回undefined;//将日期字符串转换为日期。if(typeof v==“string”&&/^\d\d\d\d-\d\dT\dd:\d\d:\d\d.d.d\dZ$/.test(v))返回新日期(v);//删除空数组和对象。if(typeof v=='object'&&!object.keys(v).length)返回undefined;返回v;});}常量ob={s: “a”,b: 43中,国家:['a','b','c'],l: 空,n: {ks:“a”,efe:null,ce:“”},d: new Date(),nan:nan,k: 未定义,emptyO:{},emptyArr:[],}常量输出=removeNil(ob);console.log(输出);console.log('测试:',ob.countries.length,typeof(ob.d))


// recursive implementation
function compact(arr) {
        const compactArray = [];
        //base case 
        if(!arr.length) return []
        if(typeof arr[0] !== "undefined" 
          && arr[0]!==null && arr[0] !== " " && 
          arr[0]!== false &&
          arr[0]!== 0){
          compactArray.push(arr[0]);
        }
        return compactArray.concat(compact(arr.slice(1)))
    }
    
    compact([1,0,false,null,undefined,"banana"])`

最简单的方法

[NaN,未定义,空,0,1,2,2000,无限].filter(布尔)