I am developing an application on AngularJS (1) and I can not figure out how to split array of items in another array group by item.
I mean I have an array of different items and I would group items by uuid like:
[
{"name": "toto", "uuid": 1111},
{"name": "tata", "uuid": 2222},
{"name": "titi", "uuid": 1111}
];
Is going to be:
[
[
{"name": "toto", "uuid": 1111},
{"name": "titi", "uuid": 1111}
],
[
{"name": "tata", "uuid": 2222}
]
];
I have tried loop and loop again on forEach function but it's very long if my array is long
You could use a hash table and collect the object in the arrays of the hash table.
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; }
You can use reduce
and Object.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);
You can also use an established library like lodash to make it a lot simpler and save yourself the trouble:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.