Skip to content

Instantly share code, notes, and snippets.

@rijkvanzanten
Created June 23, 2017 13:01
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 rijkvanzanten/acfe6d23425aee06c8f457048cb46a48 to your computer and use it in GitHub Desktop.
Save rijkvanzanten/acfe6d23425aee06c8f457048cb46a48 to your computer and use it in GitHub Desktop.
Convert array of objects w/ timestamp to object by date
/**
* Convert array of objects w/ timestamp to object by date
* @param {Array} messages Messages to convert
* @return {Object} Messages grouped by date YYYY-MM-DD
*/
function groupMessagesByDate(messages = []) {
const groupedMessages = {};
messages.forEach(message => {
const {timestamp: date} = message;
const groupKey = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;
if (groupedMessages[groupKey]) {
groupedMessages[groupKey] = [...groupedMessages[groupKey], message];
} else {
groupedMessages[groupKey] = [message];
}
});
return groupedMessages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment