Skip to content

Instantly share code, notes, and snippets.

@mlms13
Last active August 29, 2015 14:06
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 mlms13/aa93464e2bdc1b61eaa6 to your computer and use it in GitHub Desktop.
Save mlms13/aa93464e2bdc1b61eaa6 to your computer and use it in GitHub Desktop.
Reduce an array of reviews so that they are grouped by publication
db.reviews.find({}, function (err, result) {
if (err) next(err);
// each item in the result array looks like this
// {
// source: 'The Washington Post',
// location: 'City, State',
// review: 'Several paragraphs of review text'
// }
// sort publication alphabetically and group
// by publication
var reviews = result
.sort(function (a, b) {
if (a.source > b.source) return 1;
if (a.source < b.source) return -1;
return 0;
})
.map(function (item) {
// return something that looks like the original object
// but with the review inside an array
return {
source: item.source,
location: item.location,
reviews: [item.review]
};
})
.reduce(function (prev, curr) {
// if there was a previous item and the previous item had the same source
if (prev.length && prev[prev.length - 1].source === curr.source) {
// add the current review text to the array of reviews
prev[prev.length - 1].reviews = prev[prev.length - 1].reviews.concat(curr.reviews);
} else {
prev.push(curr)
}
return prev;
}, []);
res.render('reviews', reviews);
});
extends layout
block content
if (reviews.length)
h2= review.source
if (review.location)
span.review-location= review.location
each text in review.reviews
blockquote= text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment