2017-07-26 8 views
1

私はAngularJS(1)でアプリケーションを開発していますが、別の配列グループ内のアイテムの配列をアイテムごとに分割する方法を理解できません。キーワードで配列を要素ごとにグループ化する

私は別の項目の配列を持っているし、私のようなUUIDによるグループ項目です意味:

[ 
    {"name": "toto", "uuid": 1111}, 
    {"name": "tata", "uuid": 2222}, 
    {"name": "titi", "uuid": 1111} 
]; 

がされようとしている:

[ 
    [ 
     {"name": "toto", "uuid": 1111}, 
     {"name": "titi", "uuid": 1111} 
    ], 
    [ 
     {"name": "tata", "uuid": 2222} 
    ] 
]; 

私はforEachの上で再びループ、ループを試してみました私の配列が長い場合は非常に長いです

+0

あなたは試してみました何? – Weedoze

+0

*試したことがあります。* - 試したコードを見せてみませんか? – Weedoze

+0

inutile @Weedoze – pascalegrand

答えて

1

あなたはハッシュテーブルを使用して、ハッシュテーブルの配列内のオブジェクトを集めることができました。

var array = [{ name: "toto", uuid: 1111 }, { name: "tata", uuid: 2222 }, { name: "titi", uuid: 1111 }], 
 
    hash = Object.create(null), 
 
    result = []; 
 

 
array.forEach(function (a) { 
 
    if (!hash[a.uuid]) { 
 
     hash[a.uuid] = []; 
 
     result.push(hash[a.uuid]); 
 
    } 
 
    hash[a.uuid].push(a); 
 
}); 
 

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

0

reduceObject.values()

let a = [ 
 
    {"name": "toto", "uuid": 1111}, 
 
    {"name": "tata", "uuid": 2222}, 
 
    {"name": "titi", "uuid": 1111} 
 
]; 
 

 
let b = Object.values(a.reduce((a,b) => { 
 
    a[b.uuid] = a[b.uuid] ? a[b.uuid].concat(b) : [b]; 
 
    return a; 
 
}, {})); 
 

 
console.log(b);

-2

また、それがずっと簡単にし、自分に手間を省くためにlodashのような確立ライブラリを使用することができます。

let arr = [ 
 
    {"name": "toto", "uuid": 1111}, 
 
    {"name": "tata", "uuid": 2222}, 
 
    {"name": "titi", "uuid": 1111} 
 
] 
 

 
let grouped = _.groupBy(arr, 'uuid') 
 

 
console.log(grouped) 
 
console.log(Object.values(grouped))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

関連する問題