Remove empty elements from an array in Javascript

后端 未结 30 2486
无人共我
无人共我 2020-11-21 09:53

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条回答
  • 2020-11-21 10:38

    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 );
    
    0 讨论(0)
  • 2020-11-21 10:40

    Removing all empty elements

    If an array contains empty Objects, Arrays, and Strings alongside other empty elements, we can remove them with:

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

    Simple compacting (removing empty elements from an array)

    With ES6:

    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)

    With plain 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)

    0 讨论(0)
  • 2020-11-21 10:41

    This might help you : 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));
                });
            };
    
    0 讨论(0)
  • 2020-11-21 10:42

    I'm simply adding my voice to the above “call ES5's Array..filter() with a global constructor” golf-hack, but I suggest using Object instead of String, Boolean, or Number as suggested above.

    Specifically, ES5's filter() already doesn't trigger for undefined elements within the array; so a function that universally returns true, which returns all elements filter() hits, will necessarily only return non-undefined elements:

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

    However, writing out ...(function(){return true;}) is longer than writing ...(Object); and the return-value of the Object constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, Object is a short-hand for 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]
    
    0 讨论(0)
  • 2020-11-21 10:42
    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.

    0 讨论(0)
  • 2020-11-21 10:43

    @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;
      };
    }
    
    0 讨论(0)
提交回复
热议问题