Skip to content

Instantly share code, notes, and snippets.

@zhenghaohe
Created April 10, 2021 06: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 zhenghaohe/d22596f2051108ca60667c62f5254bac to your computer and use it in GitHub Desktop.
Save zhenghaohe/d22596f2051108ca60667c62f5254bac to your computer and use it in GitHub Desktop.
input = [
['google.com', '20'],
['mail.google.com', '10'],
['zhenghao.mail.google.com', '10'],
]
output = { 'google.com': 40, 
'mail.google.com': 20, 
'zhenghao.mail.google.com': 10 } 
function fn(array) {
return array.reduce((result, [url, count]) => {
const urlArr = url.split('.')
for (let i = urlArr.length - 2; i >= 0; i--) {
const domain = urlArr.slice(i).join('.')
result[domain] = (result[domain] || 0) + Number(count)
}
return result
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment