Catalin Vasilescu
Catalin Vasilescu

Reputation: 41

Grouping elements in javascript

I've created this list by grouping elements from another list (with d3.nest)

array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3},
                               {Id: "1234b", ECTS: 3}]}, 
          {key: "7S", values: [{Id: "1534a", ECTS: 5},
                               {Id: "154b", ECTS: 4},]} ]

From this list I want to create something like this:

array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},

        {key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]

Actually I want to group the data for each key (6S, 7S) by ECTS. I've tried with _.groupBy.... but is not working. The problem is that the elements that I want to group are objects, already grouped once. Any idea about how I could group the items?

Upvotes: 0

Views: 73

Answers (2)

Nishant Dixit
Nishant Dixit

Reputation: 5522

var array = [{
        key: "6S",
        values: [{
                Id: "1234a",
                ECTS: 3
            },
            {
                Id: "1234b",
                ECTS: 3
            }
        ]
    },

    {
        key: "7S",
        values: [{
                Id: "1534a",
                ECTS: 5
            },
            {
                Id: "154b",
                ECTS: 4
            },
        ]
    }
]

array = array.map(function(v1) {
    var updatedVal = v1.values.reduce(function(obj, v2) {
        obj[v2.ECTS] = obj[v2.ECTS] || [];
        obj[v2.ECTS].push({
            Id: v2.Id
        });
        return obj;
    }, {});
    v1.values = updatedVal;
    return v1;
});

console.log(array);

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

You can try following

var array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]},  {key: "7S", values: [{Id: "1534a", ECTS: 5}, {Id: "154b", ECTS: 4},]} ];


 array.forEach((obj) => {
    var values = {};
    // Iterate over array and create the updated value
    obj.values.forEach((item) => {
       values[item.ECTS] = values[item.ECTS] || [];
       values[item.ECTS].push({"Id" : item.Id});
    });
    // Set the updated value in object
    obj.values = values;

});
                  
console.log(array);

Upvotes: 1

Related Questions