Skip to content

Instantly share code, notes, and snippets.

@nolim1t
Created April 3, 2017 05:37
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 nolim1t/1d0882639e7cb6c2ceee79a582bdb8fb to your computer and use it in GitHub Desktop.
Save nolim1t/1d0882639e7cb6c2ceee79a582bdb8fb to your computer and use it in GitHub Desktop.
Javascript Sorting 3 (Sorting messages by date and then group by recipient)
var unsorted = [
{
recipient: "b",
timestamp: 1490591976873,
title: "Hello World 3"
},
{
recipient: "a",
timestamp: 1490591722787,
title: "Hello World"
},
{
recipient: "a",
timestamp: 1490591748922,
title: "Hello World 2"
},
{
recipient: "b",
timestamp: 1490591722787,
title: "Hello World"
}
];
function groupBy( array , f )
{
var groups = {};
array.forEach( function( o )
{
var group = JSON.stringify( f(o) );
groups[group] = groups[group] || [];
groups[group].push( o );
});
return Object.keys(groups).map( function( group )
{
return groups[group];
})
}
function compare(objA, objB) {
if (objA.timestamp !== undefined && objB.timestamp !== undefined) {
if (objA.timestamp < objB.timestamp) {
return -1;
} else if (objA.timestamp > objB.timestamp) {
return 1;
} else {
return 0;
}
} else {
// Error
return;
}
}
var inbox = [];
var r = unsorted.sort(compare).reverse().reduce(function(reduced, recipient) {
if (inbox[recipient.recipient] == undefined) {
inbox[recipient.recipient] = [recipient];
} else {
inbox[recipient.recipient].push(recipient);
}
console.log(reduced);
return reduced;
}, {});
console.log(inbox);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment