looking for some solutions? You are welcome.

SOLVED: How to group array based on common value?

user1687891:

I have data structure like below:

a : { active: true, key: "first", page: 1 },
b : { active: true, key: "second", page: 1 },
c : { active: true, key: "third", page: 2 },
d : { active: true , key: "fourth", page: 2 },
e : { active: false , key: "fifth", page: 3 },

From this data, first I need to find data with active status true then I need to create a new array containing sub array with same page number. I need something like this.

[
    ["first", "second"],
    ["third", "fourth"],
    ["fifth"]
]

What I have tried is:

let myArray = Object.entries(dashboardKeyConfiguration).filter(x => x[1]["active"]);

var groups = [];
        for (var i = 0; i < myArray.length; i++) {
            var groupName = myArray[i][1]["page"];
            if (!groups[groupName]) {
                groups[groupName] = [];
            }
            groups[groupName].push(myArray[i][1]["key"]);
        }
        myArray = [];
        console.log(groups);

It is inserting empty as first item like this:

(3) [empty, Array(2), Array(2)]



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent