如何从jquery中的数组中删除空值?

时间:2016-02-10 08:10:28

标签: javascript jquery

如何从数组中删除空值。 例如

var data = [
    ["George L. Bunting", null, null, null],
    ["Marc G. Bunting", null, null, null],
    ["Suzanne F. Cohen", null, null, null],
    ["Rosalee  Davison", null, null, null],
    ["Richard  Davison", null, null, null],
    ["Marilynn K. Duker", null, null, null],
    ["Dale  McArdle", null, null, null],
    [null, null, null, null],
    [null, null, null, null],
    [null, null, null, null]
]

我要求得到这样的

data = [
    ["George L. Bunting", null, null, null],
    ["Marc G. Bunting", null, null, null],
    ["Suzanne F. Cohen", null, null, null],
    ["Rosalee  Davison", null, null, null],
    ["Richard  Davison", null, null, null],
    ["Marilynn K. Duker", null, null, null],
    ["Dale  McArdle", null, null, null]
]

并删除单词'Dale McArdle'之间的空格 - > 'Dale McArdle'?

$("input[id*=btnListGeneratorwithDetails]").click(function() {
    $("[id*=hdnfldSpreadSheetData]").val(JSON.stringify(handsontable.getData()));

    strEntityList = JSON.stringify(handsontable.getData());
    //alert(strEntityList);
});

1 个答案:

答案 0 :(得分:1)

您可以结合使用.filter.every

var data = [
    ["George L. Bunting", null, null, null],
    ["Marc G. Bunting", null, null, null],
    ["Suzanne F. Cohen", null, null, null],
    ["Rosalee  Davison", null, null, null],
    ["Richard  Davison", null, null, null],
    ["Marilynn K. Duker", null, null, null],
    ["Dale  McArdle", null, null, null],
    [null, null, null, null],
    [null, null, null, null],
    [null, null, null, null]
]
data = data.filter(function(entry) {
    return !entry.every(function(value) {
        return value === null;
    });
});
console.log(data);