代码之家  ›  专栏  ›  技术社区  ›  Tamas Czinege

在Javascript中从数组中删除空元素

  •  821
  • Tamas Czinege  · 技术社区  · 17 年前

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

    39 回复  |  直到 6 年前
        1
  •  1508
  •   vsync    7 年前

    简单方法:

    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]
    

    或-(仅适用于 仅有一个的 “文本”类型的数组项

    ['','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
    
    arr // [1,2,3,3,[],Object{},5,6]
    


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


    更新-只是另一种快速、酷的方式(使用ES6):

    var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
        temp = [];
    
    for(let i of arr)
        i && temp.push(i); // copy each non-empty value to the 'temp' array
    
    arr = temp;
    
    arr // [1, 2, 3, 3, 4, 4, 5, 6]
    

    删除空值

    ['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)
    
    // ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]
    
        2
  •  1374
  •   Christian C. Salvadó    7 年前

    编辑: 这个问题在大约九年前就得到了回答,当时世界上没有多少有用的内置方法 Array.prototype .

    现在,当然,我建议您使用 filter 方法

    请记住,此方法将返回给您 通过您提供给它的回调函数的条件的元素。

    例如,如果要删除 null undefined

    var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
    
    var filtered = array.filter(function (el) {
      return el != null;
    });
    
    console.log(filtered);

    这将取决于你认为是“空”的,例如,如果你在处理字符串,上面的函数就不能移除空字符串的元素。

    法尔西 ,其中包括一个空字符串 "" , 0 , NaN , , false

    你可以转到 滤器 方法 Boolean

    var filtered = array.filter(Boolean);
    

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

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

    滤器 方法传递返回true的回调,例如:

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

    旧答案: 别这样!

    我使用此方法扩展本机阵列原型:

    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,,,,]);
    
        3
  •  255
  •   Soviut    8 年前

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

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

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

    返回:

    ["hello", 0, 1, 100, " "]
    
        4
  •  141
  •   Andreas Louv    13 年前

    仅一行:

    [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]
    
        5
  •  135
  •   Alnitak    12 年前

    Array.filter 使用琐碎的 return true 回调函数,例如:

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

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

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

    请注意,这不会删除 null 条目或具有显式 undefined

        6
  •  98
  •   tsh    5 年前

    要移除孔,应使用

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

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

    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, false, "", 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
    
        7
  •  59
  •   Tomás Senart    15 年前

    这是一个干净的方法。

    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"]
    
        8
  •  42
  •   j08691    9 年前

    ['a','b','',,,'w','b'].filter(v => v);
    
        9
  •  41
  •   deadcoder0904    6 年前

    ES6:

    let newArr = arr.filter(e => e);
    
        10
  •  33
  •   DarckBlezzer RichieHindle    4 年前

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

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

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

    • 第一种方式:

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

      const clearArray = arr.filter(Boolean); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
      

    const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
    console.log("arr.filter(i => i)", arr.filter(i => i));
    console.log("arr.filter(Boolean)", arr.filter(Boolean));
        11
  •  22
  •   Yves M.    11 年前

    带下划线/Lodash:

    一般用例:

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

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

    看见 lodash documentation for without

        12
  •  16
  •   Luis Perez    14 年前

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

    _.紧凑型(阵列)

    =>[1, 2, 3]

        13
  •  15
  •   Erik Johansson    17 年前

    @阿尔尼塔克

    实际上,如果添加一些额外的代码,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;
      };
    }
    
        14
  •  14
  •   Josh Bedo    11 年前

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

    _.without(["text", "string", null, null, null, "text"], null)
    // => ["text", "string", "text"]
    
        15
  •  8
  •   Jason Bunting    17 年前

    您可能会发现,与按照建议尝试循环和拼接相比,在阵列上循环并使用要保留的项目构建新阵列更容易,因为在循环过程中修改阵列的长度可能会带来问题。

    你可以这样做:

    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]
    

        16
  •  6
  •   VIJAY P    10 年前

    关于这个(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"]
    
        17
  •  6
  •   Gapur Kassym    8 年前

    const array = [1, 32, 2, undefined, 3];
    const newArray = array.filter(arr => arr);
    
        18
  •  4
  •   Goku Nymbus    11 年前

    当使用上面投票率最高的答案(第一个示例)时,我得到了字符串长度大于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"]
    
        19
  •  3
  •   ELLIOTTCABLE    13 年前

    我只是将我的声音添加到上述ES5的通话中 Array..filter() 用一个全局构造器,但我建议使用 Object String , Boolean Number 如上所述。

    具体来说,ES5的 filter() 已经不会触发 undefined 数组中的元素;所以一个普遍返回的函数 true ,返回 全部的 元素 过滤器() 未定义

    > [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) ; 以及 对象 构造函数将在 任何情况 对象 是的缩写 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]
    
        20
  •  3
  •   KARTHIKEYAN.A    9 年前
    var data = [null, 1,2,3];
    var r = data.filter(function(i){ return i != null; })
    

    console.log(r) 
    

    [1,2,3]

        21
  •  3
  •   Zalom    6 年前

    删除所有空元素

    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) => {
        return ![null, undefined, ''].includes(obj)
      }).filter((el) => {
        return typeof el != "object" || Object.keys(el).length > 0
      })
    )
    
    console.log(JSON.parse(filtered))

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

    const arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
    
    let filtered = arr.filter((obj) => { return ![null, undefined].includes(obj) })
    
    console.log(filtered)

    使用纯Javascript->

    var arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
    
    var filtered = arr.filter(function (obj) { return ![null, undefined].includes(obj) })
    
    console.log(filtered)
        22
  •  3
  •   Kamil Kiełczewski    5 年前

    in 操作人员

    let a = [1,,2,,,3];
    let b = a.filter((x,i)=> i in a);
    
    console.log({a,b});
        23
  •  2
  •   JessyNinja    15 年前

    js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
    1,2,3,3,0,4,4,5,6
    
        24
  •  2
  •   GameAlchemist    13 年前

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

    http://jsperf.com/remove-null-items-from-array

    下面的代码将不可枚举的“removeNull”方法添加到数组中,该数组为菊花链返回“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 } ) ;
    
        25
  •  1
  •   Joe Pineda    17 年前

    这是有效的,我在实验室测试过 AppJet

    /* 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]
    */
    
        26
  •  1
  •   sqram    11 年前
    foo = [0, 1, 2, "", , false, 3, "four", null]
    
    foo.filter(function(e) {
        return e === 0 ? '0' : e
    })
    

    返回

    [0, 1, 2, 3, "four"]
    
        27
  •  1
  •   cluster1    10 年前

    “误用”用于。。。在(对象成员)循环中。 =>只有真实值出现在循环体中。

    // --- 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);
    
        28
  •  1
  •   Sandeep M    9 年前

    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));
                });
            };
    
        29
  •  1
  •   GGO    8 年前
    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

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

        30
  •  1
  •   Bhupesh Kumar    6 年前

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