2014-02-06 29 views
0

有沒有辦法合併以下數組:合併數組中的JavaScript

var arr = [["2014-2-5", "2014-2-4", "2014-1-9", "2014-1-8"], [], ["2014-2-4"], [], []] 

,並使它看起來像:

["2014-2-5", "2014-2-4", "2014-1-9", "2014-1-8", "2014-2-4"] 

我試圖console.log($.merge(arr)); ,但它無法正常工作。

感謝

+0

哦,是絕對複製。忽略我的答案。使用'[] .concat.apply([],arr);' – bits

回答

0

使用Array的reduce結合concat

arr.reduce(function(previousValue, currentValue, index, array){ 
    return previousValue.concat(currentValue); 
}); 
0

不合並但flatten-

Array.prototype.flatten= function(){ 
    var A= []; 
    this.forEach(function(itm){ 
     if(itm!= undefined){ 
      if(!itm.flatten) A.push(itm); 
      else A= A.concat(itm.flatten()); 
     } 
    }); 
    return A; 
} 

var arr= [["2014-2-5", "2014-2-4", "2014-1-9", 
"2014-1-8"], [], ["2014-2-4"], [], []]; 
arr.flatten(); 

// returned value: (Array) 
['2014-2-5', '2014-2-4', '2014-1-9', '2014-1-8', '2014-2-4']