2016-06-12 67 views
0

合併兩個陣列我有兩個陣列(ARR1 & ARR2)這樣通過分組基於第一陣列的元件在Javascript

var arr1 = ["A","B","C"]; 

var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]]; 

我想將它們組在一起成爲根據的值在JavaScript第三陣列第一陣列。所需的輸出:

arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ] 

注:我有arr2開始,並能夠檢索第一個值,並刪除重複到arr1。

請指教。

回答

2

嘗試這樣

var arr1 = ["A", "B", "C"]; 

var arr2 = [ 
    ["A", "aa"], 
    ["A", "ab"], 
    ["A", "ac"], 
    ["B", "ba"], 
    ["B", "bb"], 
    ["B", "bc"], 
    ["C", "ca"], 
    ["C", "cb"] 
]; 
var newVal = arr1.map(function(x) { 
    var filter = arr2.filter(function(y) { 
    return y[0] == x; 
    }).map(function(y) { 
    return y[1]; 
    }); 
    return [x, filter]; 
}) 
console.log(newVal); 

DEMO

1

注:我不得不ARR2開始與和能夠檢索第一個值並刪除重複到ARR1。

而不是創建arr1作爲一箇中間步驟,我可能會創建一個對象作爲中間步驟:

var obj = arr2.reduce(function(a,b){ 
    if (!a[b[0]]) a[b[0]] = []; 
    a[b[0]].push(b[1]); 
    return a; 
},{}); 

// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]} 

該對象轉換爲所需輸出數組:

var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; }); 
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]] 

如果你實際上需要arr1陣列作爲其他的東西,那麼:

var arr1 = Object.keys(obj); 
// ["A", "B", "C"] 

但是請注意,obj是進一步處理相當有用的,因爲如果你需要得到與"B"關聯的值,你不需要再通過一個數組進行搜索,你可以簡單地說obj["B"](這將給陣列["ba","bb","bc"]) 。所以第二個"B"的值是obj["B"][1]

進一步閱讀: