Removing undefined values from Array

后端 未结 13 1990
死守一世寂寞
死守一世寂寞 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:16
    var data = Object.keys(data)
    

    This will remove undefined values but array index will change

    0 讨论(0)
  • 2020-12-02 17:18
    var arr1 = [NaN, 0, 15, false, -22, '',undefined, 47, null];
    
    var array1 = arr1.filter(function(e){ return e;});
    
    document.write(array1);
    

    single lined answer

    0 讨论(0)
  • 2020-12-02 17:18
    data.filter(Boolean)
    

    Is the most short and readable way to do it.

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

    As Diogo Capela said, but where 0 is not filtered out as well.

    [].filter(item => item !== undefined && item !== null)
    
    0 讨论(0)
  • 2020-12-02 17:21

    If you have an array of objects and want to remove all null and undefined items:

    [].filter(item => !!item);
    
    0 讨论(0)
  • Inline using lambda

    result.filter(item => item);
    
    0 讨论(0)
提交回复
热议问题