How to get users id after filter and map
You could also sort
your services on the amount
. Then you can group them by the providerId
and finally map over the providers to get the output you want:
const services = [ { id: 1, providerId: 1, amount: 250000 }, { id: 4, providerId: 3, amount: 280900 }, { id: 6, providerId: 3, amount: 31000 }, { id: 2, providerId: 2, amount: 58600 }, { id: 3, providerId: 1, amount: 13000 }, { id: 5, providerId: 2, amount: 5000 }, { id: 3, providerId: 3, amount: 59900 }, { id: 6, providerId: 3, amount: 9500 } ]
const providers = [ { id: 1, name: 'Netflix' }, { id: 2, name: 'Comcast' }, { id: 3, name: 'Verizon' } ]
let grouped = services
.sort((a,b) => b.amount - a.amount) // sort `desc`
.reduce((r,c) => ((r[c.providerId] = r[c.providerId] || []).push(c), r), {})
let result = providers.map(p => ({name: p.name, user: grouped[p.id][0].id}))
console.log(result)
You could also skip the sort
above and check the amount
and based on that either push
or unshift
:
const services = [ { id: 1, providerId: 1, amount: 250000 }, { id: 4, providerId: 3, amount: 280900 }, { id: 6, providerId: 3, amount: 31000 }, { id: 2, providerId: 2, amount: 58600 }, { id: 3, providerId: 1, amount: 13000 }, { id: 5, providerId: 2, amount: 5000 }, { id: 3, providerId: 3, amount: 59900 }, { id: 6, providerId: 3, amount: 9500 } ]
const providers = [ { id: 1, name: 'Netflix' }, { id: 2, name: 'Comcast' }, { id: 3, name: 'Verizon' } ]
let groupedById = services.reduce((acc, cur) => {
let k = cur.providerId
acc[k] = acc[k] || []
if(acc[k][0] && acc[k][0].amount > cur.amount) acc[k].push(cur)
else acc[k].unshift(cur)
return acc
}, {})
let result = providers.map(({name, id}) => ({name, user: groupedById[id][0].id}))
console.log(result)
This way you only have one Array.reduce
and one Array.map
which will be more performant
than your original version which has forEach
, filter
and map
.