Just stumbled across this scenario in some code I'm writing and was curious what the "right" method is. Say for example I have a large array of objects which I need to group by a certain property, but then the order of the groups matter.
Ex. Obj :
var obj = {
"groupName" : ["Group1", "Group2" ]
}
So if I have a bunch of these objects in an array, it's annoying to iterate over each object, iterate over it's groupName property, check another array like "groups" to see if the group exists, if not create it, and add the object.
Does it make sense to have an object called groups with properties matching the group names, group the objects that way, and then at the end turn groups into an array (naturally using some sort of precedence field in the group to order).
ex.
var groups = {
"Group1": {
"precedence":1,
"objArray": []
}
}
Then you can group like so, do a forEach on array of objs, forEach on obj.groupnames, if groupname in groups push obj, else groups.groupname is a new group, get precedence from a lookup table, push obj to this group.
At the end, enumerate all props of groups and add to groupsArray, then sort by precedence.
Is this more/less efficient than just using arrays? Makes less sense? Is there a better way to do this? I got it working with the above method, I was just curious from more of a theoretical sense whether this is common practice vs. inefficient and bulky :P.
Thanks!
EDIT:
A start/end result to better explain things:
var obj1 = {
"groupsIBelongTo" : ["A", "B"];
};
var obj2 = {
"groupsIBelongTo" : ["B", "C"];
};
var obj3 = {
"groupsIBelongTo" : ["A", "C"];
};
var objArray = [ obj1, obj2, obj3];
I want to create an array of groups that contain the appropriate objs. Assume the precedence is B, A, C , the end result should be as such:
var groups = [ {
"groupName" : "B",
"objs" : [obj1, obj2]
},
{
"groupName" : "A",
"objs" : [obj1, obj3]
},
{
"groupName" : "C",
"objs" : [obj2, obj3]
},
]