2017-07-26 75 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>