Removing undefined values from Array

后端 未结 13 1988
死守一世寂寞
死守一世寂寞 2020-12-02 16:52

In certain situations, it may happen that we have undefined or generally falsy values in Array structures. For instance when reading and filling data f

相关标签:
13条回答
  • 2020-12-02 17:08

    The solution with Array.filter will actually keep the array unchanged and create a new array without the undesired items. If you want to clean an array without duplicating it, you can use this:

    for (var i = data.length-1; i >= 0; i--) {
        if (!data[i]) {
            data.splice(i, 1);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:09

    in ES6 this can be achieved by simply using using filter with function return the value like this:

    const array = [NaN, 0, 15, false, -22, '',undefined, 47, null];
    const filteredArr = array.filter(elm => elm);
    console.log(filteredArr);
    
    0 讨论(0)
  • 2020-12-02 17:10

    To use Array.prototype.filter here might be obvious. So to remove only undefined values we could call

    var data = [42, 21, undefined, 50, 40, undefined, 9];
    
    data = data.filter(function( element ) {
       return element !== undefined;
    });
    

    If we want to filter out all the falsy values (such as 0 or null) we can use return !!element; instead.

    But we can do it slighty more elegant, by just passing the Boolean constructor function, respectively the Number constructor function to .filter:

    data = data.filter( Number );
    

    That would do the job in this instance, to generally remove any falsy value, we would call

    data = data.filter( Boolean );
    

    Since the Boolean() constructor returns true on truthy values and false on any falsy value, this is a very neat option.

    0 讨论(0)
  • 2020-12-02 17:11

    You can use lodash compact method, which removes null, undefined and ''

    _.compact(data)
    
    0 讨论(0)
  • 2020-12-02 17:12

    Array.prototype.reduce() can be used to delete elements by condition from an array but with additional transformation of the elements if required in one iteration.


    Remove undefined values from array, with sub-arrays support.

    function transform(arr) {
        return arr.reduce((memo, item) => {
            if (typeof item !== "undefined") {
                if (Array.isArray(item)) item = transform(item);
                // We can transform item here.
                memo.push(item);
            }
            return memo;
        }, []);
    }
    
    let test1 = [1, 2, "b", 0, {}, "", , " ", NaN, 3, undefined, null, 5, false, true, [1, true, 2, , undefined, 3, false, ''], 10];
    
    console.log(transform(test1));
    

    Try it on jsfiddle.net/bjoy4bcc/

    0 讨论(0)
  • 2020-12-02 17:14

    ES6 single line

    data.filter(e => e)
    
    0 讨论(0)
提交回复
热议问题