2016-02-10 41 views
-1

如何從數組中刪除空值。 例如如何從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] 
] 

,並寫着 '戴爾·麥卡德爾' 之間移除空間 - > '戴爾·麥卡德爾'?

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

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

你可以在這裏找到另一副本:http://stackoverflow.com/questions/12745800/how-從數組中刪除null值從jquery – LaVomit

+0

這是一個問題。一個大的。遇到麻煩時,請嘗試[再次詢問](http://stackoverflow.com/help/how-to-ask)。 – dasdingonesin

+0

爲什麼選擇jQuery?如果它是jQuery,你爲什麼不把它標記爲這樣?另外,請一次提出一個問題。無論如何,你堅持在這個地方?你不知道如何遍歷數組嗎?你不知道如何訪問每個元素,並檢查它是否都是空值?你不知道如何去除不需要的元素? –

回答

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

+0

我沒有得到答案 –

+0

@ 0143.NetUser SO不支持'console.log'。嘗試一下你的自我。 – Oleander