With this data I am returning one object per keyword
prioritising preferedDomain
string on domain and then its higher rank
value, it is already ordered by rank so returning one object per keyword will take care of that.
This does work and I have done some performance checks and found out that doing a for loop will take longer than this.
Is there a better approach to tackle this problem?
const preferedDomain = 'prefered'
const data = [
{ keyword: 'hey', domain: 'apple', rank: 1},
{ keyword: 'hey', domain: 'apple', rank: 2},
{ keyword: 'hey', domain: 'prefered', rank: 46},
{ keyword: 'foo', domain: 'amazon', rank: 1},
{ keyword: 'foo', domain: 'amazon', rank: 2},
{ keyword: 'foo', domain: 'amazon', rank: 3},
{ keyword: 'bla', domain: 'prefered', rank: 1},
{ keyword: 'bla', domain: 'prefered', rank: 2},
{ keyword: 'bla', domain: 'prefered', rank: 3}
]
// Object map with prefered objects only
const prefered = data.reduce((acc, obj) => {
if (!acc[obj.keyword] && obj.domain === preferedDomain) acc[obj.keyword] = obj
return acc
}, {})
// If keyword is on prefered object use that, otherwise the first entry
const res = Object.values(
data.reduce((acc, obj) => {
if (!acc[obj.keyword]) acc[obj.keyword] = prefered[obj.keyword] ?? obj
return acc
}, {})
)
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }