Created
March 25, 2018 04:58
-
-
Save frnsys/681c50312fe4a584c3794b34885cf5ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dummy data | |
let orders = [{ | |
userId: 0 | |
}, { | |
userId: 1 | |
}, { | |
userId: 1 | |
}]; | |
let users = [{ | |
id: 0, | |
locationId: 0 | |
}, { | |
id: 1, | |
locationId: 1 | |
}] | |
let locations = [{ | |
id: 0, | |
state: 'NY' | |
}, { | |
id: 1, | |
state: 'CA' | |
}] | |
// map order.userId->order count | |
let userCounts = orders.reduce((acc, order) => { | |
acc[order.userId] = acc[order.userId] + 1 || 1; | |
return acc; | |
}, {}); | |
// map user.locationId->user-order count | |
let locationCounts = users.reduce((acc, user) => { | |
let orderCount = userCounts[user.id]; | |
acc[user.locationId] = acc[user.locationId] + orderCount || orderCount; | |
return acc; | |
}, {}); | |
// find location with the highest count | |
let highest = locations.reduce((acc, location) => { | |
// check if this location's order count is higher | |
// than our current best. if so, return it as the current best. | |
let orderCount = locationCounts[location.id]; | |
if (orderCount > acc.count) { | |
return {state: location.state, count: orderCount} | |
// otherwise, just return the current best | |
} else { | |
return acc; | |
} | |
}, {state: null, count: 0}); | |
console.log(highest.state); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment