javascript - Group by element in array by keyword -
i developing application on angularjs (1) , can not figure out how split array of items in array group item.
i mean have array of different items , group items uuid like:
[ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ]; is going be:
[ [ {"name": "toto", "uuid": 1111}, {"name": "titi", "uuid": 1111} ], [ {"name": "tata", "uuid": 2222} ] ]; i have tried loop , loop again on foreach function it's long if array long
you use hash table , collect object in arrays of 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; }
Comments
Post a Comment