Created
April 3, 2017 05:37
-
-
Save nolim1t/1d0882639e7cb6c2ceee79a582bdb8fb to your computer and use it in GitHub Desktop.
Javascript Sorting 3 (Sorting messages by date and then group by recipient)
This file contains 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
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