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

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


当前回答

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

其他回答

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

就地解决方案:

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

删除所有空元素

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

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(已过滤)

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

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

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

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