Created
September 8, 2014 19:35
-
-
Save mlms13/7fc3a180d2240cd67630 to your computer and use it in GitHub Desktop.
Map/Reduce to group blog posts by year
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
// Assume you retrieve an array of blog posts, with each item in the array looking like: | |
// { | |
// title: "", | |
// date: new Date(), | |
// ... other properties that are less interesting | |
// } | |
// And we want to sort this array by date, print a pretty date, | |
// and group posts from the same year under the same heading. | |
var data = [/* lots of objects like the one we described */]; | |
// friendly names for months | |
var months = ['January', 'February', 'March', 'April' /* I'm lazy... you get the idea */] | |
var postsByDate = data.sort(function (a, b) { | |
// get date as integer and sort so that older comes first | |
return a.date.getTime() - b.date.getTime(); | |
}) | |
.map(function (item) { | |
// overwrite the date to a nice, friendly object | |
item.date = { | |
year: item.date.getFullYear(), | |
month: months[item.date.getMonth()], | |
day: item.date.getDate() | |
}; | |
return item; | |
}) | |
.reduce(function (prev, curr) { | |
// if the array is empty, or if the last object's year doesn't match our current year | |
if (!prev.length || prev.year !== curr.date.year) { | |
// push a new year to the array | |
// and add our current item to the array of items | |
prev.push({ | |
year: curr.date.year, | |
items: [curr] | |
}); | |
} else { | |
// otherwise, the prev year matches our current year | |
// so just push our current item | |
prev.items.push(curr); | |
} | |
return prev; | |
}, []); | |
// after all that, you should end up with an array that looks something like this | |
// [{ | |
// year: 2000, | |
// items: [{ | |
// title, date, and other post properties | |
// }] | |
// }, { | |
// year: 2004, | |
// items: [{...}, {...}] | |
// }] | |
// Now you can pass this to a template, which can uses nested loops. | |
// The outer loop steps through each year, printing a new heading for each. | |
// The inner loop steps through each `item` which is just an object | |
// representing the original blog post | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment