Home > Blockchain >  JS Group objects by property
JS Group objects by property

Time:12-09

I have an array like this:

[
{groupId:4,group:"g4",name:"Luke",value:12},
{groupId:3,group:"g3",name:"Mike",value:21},
{groupId:3,group:"g3",name:"Greg",value:33},
{groupId:4,group:"g4",name:"Harry",value:42},
{groupId:4,group:"g4",name:"David",value:13},
{groupId:4,group:"g4",name:"John",value:14},
{groupId:3,group:"g3",name:"Joe",value:23},
{groupId:2,group:"g2",name:"Albert",value:32},
{groupId:2,group:"g2",name:"Marie",value:25}
]

I want to group it by group name, write out the group(order doesn't matter) and id on the screen first, then all the name/value pairs underneath the group name that belong to that group. After that the same for all other groups...so my screen would look like this:

g4:4
Luke:12
Harry:42
David:13
John:14
g3:3
Mike:21
Greg:33
Joe:23
g2:2
Albert:32
Marie:25

How can I achieve this?

CodePudding user response:

I suppose you need something like this

function printGrouped(objArray) {
    let out = {};
    for (var i = 0; i < objArray.length; i  ) {
        let obj = objArray[i]
        if (!out.hasOwnProperty(obj.group)) {
            out[obj.group] = [];
        }
        out[obj.group].push(obj);
    }
    for (group in out) {
        console.log(group);
        out[group].forEach(function(obj) {
            console.log(obj.name   ":"   obj.value);
        });
    }
}
  • Related