2017-04-01 109 views
1

我有一個多維數組這樣的:項目分組在索引

var arr = [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ]; 

,我想(根據匹配arr[i][2]值分組每個子陣列),以使它像這樣:

var arr = [ [[x,x,1]] , [[x,x,2],[x,x,2]] , [[x,x,3],[x,x,3],[x,x,3]] ]; 

我的嘗試越來越囉嗦,我很慚愧地在這裏發帖。任何有效的建議非常感謝!

回答

1

Array#forEach溶液。

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]], obj = {}; 
 

 
arr.forEach(v => (obj[v[2]] || (obj[v[2]] = [])).push(v)); 
 
var res = Object.keys(obj).map(v => obj[v]); 
 

 
console.log(JSON.stringify(res));

1

您可以先使用一個對象對數組進行分組,然後使用map()Object.keys()作爲結果返回數組。

var arr = [["x","x", 1],["x","x", 2],["x","x", 2],["x","x", 3],["x","x", 3],["x","x", 3]]; 
 

 
var obj = {} 
 
arr.forEach(function(e) { 
 
    if(!obj[e[2]]) obj[e[2]] = [] 
 
    obj[e[2]].push(e) 
 
}); 
 

 
var result = Object.keys(obj).map(e => obj[e]); 
 
console.log(JSON.stringify(result))

1

var x = 'x'; 
 
var arr= [ [x,x,1] , [x,x,2] , [x,x,2] , [x,x,3] , [x,x,3] , [x,x,3] ]; 
 

 
var working = arr.reduce(function(acc, current) { 
 
    (acc[current[2]] || (acc[current[2]] = [])).push(current); 
 
    return acc; 
 
}, {}); 
 

 
var result = Object.keys(working).map(function(k) { return working[k] }); 
 

 
console.log(JSON.stringify(result)); // stringified just to avoid scrolling

1

你可以使用一個Map併產生Array#reduce在一個循環的新陣列。

var array = [['x', 'x', 1], ['x', 'x', 2], ['x', 'x', 2], ['x', 'x', 3], ['x', 'x', 3], ['x', 'x', 3]], 
 
    grouped = array.reduce((map => 
 
     (r, a) => 
 
      (!map.has(a[2]) && map.set(a[2], r[r.push([]) - 1]), map.get(a[2]).push(a), r) 
 
     )(new Map), []); 
 

 
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }