Skip to content

Instantly share code, notes, and snippets.

@frnsys
Created March 25, 2018 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frnsys/681c50312fe4a584c3794b34885cf5ba to your computer and use it in GitHub Desktop.
Save frnsys/681c50312fe4a584c3794b34885cf5ba to your computer and use it in GitHub Desktop.
// 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