const total = _(database) // Wrap json in lodash object
.map(store => store.hats) // Get all hats by all stores
.flatten() // Merge all hat arrays, plus remove any empty ones
.countBy('id').sortBy() // Get amounts by hat id and sort in asc order
.slice(-3).sum() // Sum top 3;