-1

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?

OmarLittle
  • 423
  • 1
  • 9
  • 18
  • Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – tevemadar Dec 09 '22 at 13:37

2 Answers2

1

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);
        });
    }
}
rib
  • 94
  • 6
0

Single loop and Array.reduce method

const objArray = [
    { 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 },
];

function sortBygroup(a, b) {
    if (a.group > b.group) return -1;
    else if (a.group < b.group) return 1;

    return 0;
}
objArray.sort(sortBygroup);

const output = objArray.reduce((acc, crt) => {
    if (!acc[crt.group]) {
        acc[crt.group] = {};
        console.log(crt.group);
    }
    console.log(crt.name + ":" + crt.value);
    return acc;
}, {});
Anil kumar
  • 1,216
  • 4
  • 12