Last active
October 18, 2018 05:31
-
-
Save beall49/81f86ac147883f120c8abcab62850ac3 to your computer and use it in GitHub Desktop.
Group buckets by date
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
/** | |
* @function groupBucketsByDate | |
* @desc This takes an array of objects and a date key to group off of. | |
* It then will group all of the objects by that date key and will a distinct list | |
* of dates and an array of counts for each date | |
* @param {Object[]} buckets - An array of date buckets/objects | |
* @param {string} key - The key to group the items off of | |
* @param {Object} buckets[].bucket - A single date bucket in the array | |
* @param {number} bucket.doc_count - The count of items for this particular bucket | |
* @example const groups = groupBucketsByDate(buckets, 'key_as_string'); | |
* @return {Object} A list of values and counts that can be summed | |
*/ | |
const groupBucketsByDate = (buckets, key) => { | |
return buckets.reduce((groups, bucket) => { | |
const date = bucket[key]; | |
const bucketCount = (bucket.doc_count || 0); | |
const count = parseInt(groups[date] || 0); | |
groups[date] = bucketCount + count; | |
return groups; | |
}, {}); | |
} | |
/** | |
* @function groupBucketsByDateToArray | |
* @description Same as above, just returns an array of objects | |
* @example const groups = groupBucketsByDate(buckets, 'key_as_string'); | |
* @param buckets | |
* @param key | |
* @returns {Object[]} An array of dates and count objects | |
*/ | |
const groupBucketsByDateToArray = (buckets, key) => { | |
return buckets.reduce((groups, bucket) => { | |
const date = bucket[key]; | |
const count = (bucket.doc_count || 0); | |
const group = groups.find(g => g.date === date); | |
if (group) { | |
group.count += count; | |
return groups; | |
} | |
grouped.push({ date: date, count: count }); | |
return groups; | |
}, []); | |
} | |
const buckets = [ | |
{ "key_as_string": "2038-01-01", "key": 2145916800000, "doc_count": 2032 }, | |
{ "key_as_string": "2018-08-01", "key": 1533081600000, "doc_count": 23 }, | |
{ "key_as_string": "2018-08-01", "key": 1533081600000, "doc_count": 23 } | |
]; | |
console.log(groupBucketsByDate(buckets, 'key_as_string')); | |
console.log(groupBucketsByDateToArray(buckets, 'key_as_string')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment