Attention: This page contains partner and advertising links. Therefore this page is to be understood entirety as an advertisement!
Since I lost too much time with sorting stuff while I wrote this blog, I decided to write this short article. I generate the final and static version of my website directly on my computer using gulp. The page description is stored in a json file, so I have to parse this file using javascript. Then I use moment.js and Lodash to sort the files. This is my test case: An array, that contains a date and a title entry for every blog or page entry.
var blogPosts = [{
date: "2016-10-26 13:37:00",
title: "Blog-Post 3"
}, {
date: "2016-10-24 13:37:00",
title: "Blog-Post 1"
}, {
date: "2016-10-25 13:37:00",
title: "Blog-Post 2"
}];
I want to sort the blog posts descending by date. That means the latest blog post is listed first. Important: _.sortBy()
sorts the array ascending , so I flip the whole array directly after the sort function is done using a .reverse()
.
blogPosts = _.sortBy(blogPosts, function(o) {
return new moment(o.date);
}).reverse();
Alternativ kann auch _.orderBy()
verwendet werden, das als dritten Parameter eine Sortierung akzeptiert:
blogPosts = _.orderBy(blogPosts, function(o) {
return new moment(o.date);
}, ['desc']);
If you don't trust the interpreter to treat a date object in a right way, you can just use the .format()
method of moment.js to transform the date to a definitely sortable number.
blogPosts = _.sortBy(blogPosts, function(o) {
return new moment(o.date).format('YYYYMMDD');
}).reverse();
Oder wieder alternativ mit _.orderBy()
.
blogPosts = _.orderBy(blogPosts, function(o) {
return new moment(o.date).format('YYYYMMDD');
}, ['desc']);