在JavaScript中按外部日期属性排序数组

时间:2018-06-10 16:21:48

标签: javascript node.js

我有一些.json文件可以用NodeJs读取。这些文件包含日期,标题和内容。

{
    "date": "10.06.2018",
    "title": "title goes here",
    "content": "content goes here"
}

正如您所看到的日期格式错误,它是德语日期格式。在阅读目录时,我想按日期属性对文件进行排序。

目前我只是阅读文件并尝试比较日期属性

const path = 'articles'; // the path to start from

const directoryItems = fs.readdirSync(path); // get all the files from the directory

const articles = directoryItems.map(file => JSON.parse(fs.readFileSync(`${path}/${file}`))); // convert the files to objects

const sortedArticles = articles.sort((currentFile, otherFile) => currentFile.date < otherFile.date); // sort the objects by their date

我是否必须先将日期转换为有效的JavaScript日期格式?

2 个答案:

答案 0 :(得分:1)

您可以创建一个ISO 8601合规日期,并使用该字符串进行比较。

function de2iso(date) {
    return date.replace(/(..)\.(..)\.(....)/, '$3-$2-$1');
}

var array = [{ date: "11.06.2018", title: "title goes here", content: "content goes here" }, { date: "10.06.2018", title: "title goes here", content: "content goes here" }, { date: "01.02.2018", title: "title goes here", content: "content goes here" }];

array.sort((a, b) => de2iso(a.date).localeCompare(de2iso(b.date)));

console.log(de2iso('10.06.2018'));
console.log(array);

答案 1 :(得分:1)

尝试以下方法:

&#13;
&#13;
var arr =[{"date":"10.06.2018","title":"title goes here","content":"content goes here"},{"date":"10.02.2018","title":"title goes here","content":"content goes here"}];
arr.sort(function(a,b){
  return new Date(a.date) - new Date(b.date);
});
console.log(arr);
&#13;
&#13;
&#13;