I am getting the data from a third-party API and cannot filter it beforehand. I have the following array:
[
[
User1 {
attr1: 'abc',
attr2: ['0x1', '0xa']
},
User2 {
attr1: 'def'
attr2: ['0x1', '0xb']
}
]
[
User3 {
attr1: 'ghi',
attr2: ['0x1', '0xa']
},
User4 {
attr1: 'jkl',
attr2: ['0x1', '0xb']
},
User5 {
attr1: 'mno',
attr2: ['0x1', '0xc']
}
]
]
The goal is to get the following. Essentially, I want to group users based on attr2[1] and filter out users that don't have a pair. The key would be the attr2[1].
[
{
attr2_1: '0xa',
attrs: [User1, User3]
},
{
attr2_1: '0xb',
attrs: [User2, User4]
}
]
I have a working solution but I would like to know how to solve it more elegantly.
I group the users by the second attribute
const usersByParam = _.chain(allUsers)
.flatten()
.groupBy(user => user.attr2[1])
.value()
I filter the grouped users to remove entries that don't have a pair (User5 in the example)
const filteredUsers = _.omitBy(usersByParam, (val) => {return val.length < 2})
I go through the filtered results to get my user objects
for (const key in filteredUsers) {
userArray.push({attr2_1: key, attrs: filteredUsers[key]} as User)
}
It gives me what I want, but I am sure there are more elegant ways of solving it.