Possible to do in one loop?

"branchMaterials": [
{
"branchId": 1,
"materialBalances": [
{
"balance": 20.0,
"consignmentMaterialId": 59,
"branchId": 1,
"materialName": "test"
},
"branchMaterials": [
{
"branchId": 1,
"materialBalances": [
{
"balance": 20.0,
"consignmentMaterialId": 59,
"branchId": 1,
"materialName": "test"
},
api returns this, shouldve been grouped by materialName can we do that in one loop?
Solution:
groupBy(branchMaterials.flatMap(branchMaterial => branchMaterial.materialBalances), materialBalance => materialBalance.materialName)
groupBy(branchMaterials.flatMap(branchMaterial => branchMaterial.materialBalances), materialBalance => materialBalance.materialName)
...
Jump to solution
10 Replies
lolking0
lolking016mo ago
came up with this rn
const ungroupedBranchMaterials = branchMaterials.reduce((acc, branchMaterial) => {
const { branchId, materialBalances } = branchMaterial;
const ungroupedMaterials = materialBalances.map(material => ({ branchId, material }));
return [...acc, ...ungroupedMaterials];
}, []);



const groupedByMaterialName = groupBy(ungroupedBranchMaterials, 'material.materialName');

const ungroupedBranchMaterials = branchMaterials.reduce((acc, branchMaterial) => {
const { branchId, materialBalances } = branchMaterial;
const ungroupedMaterials = materialBalances.map(material => ({ branchId, material }));
return [...acc, ...ungroupedMaterials];
}, []);



const groupedByMaterialName = groupBy(ungroupedBranchMaterials, 'material.materialName');

better way to do this?
Solution
NickServ
NickServ16mo ago
groupBy(branchMaterials.flatMap(branchMaterial => branchMaterial.materialBalances), materialBalance => materialBalance.materialName)
groupBy(branchMaterials.flatMap(branchMaterial => branchMaterial.materialBalances), materialBalance => materialBalance.materialName)
lolking0
lolking016mo ago
Thanks you're a god @nickserv
NickServ
NickServ16mo ago
Note that I'm using groupBy from the TC39 proposal
lolking0
lolking016mo ago
I'm using lodash so no worries
NickServ
NickServ16mo ago
You'll have to use a supported environment or polyfill it, and then replace it with Map.groupBy or Object.groupBy depending on what you want it to return
NickServ
NickServ16mo ago
You don't need lodash for this imo
lolking0
lolking016mo ago
we already use it in the project
NickServ
NickServ16mo ago
In that case you should probably use their primitives instead of my callback functions
lolking0
lolking016mo ago
okk thanks
Want results from more Discord servers?
Add your server