简体   繁体   English

在JavaScript中按外来日期属性对数组进行排序

[英]sort array by foreign date property in JavaScript

I have some .json files to read with NodeJs. 我有一些要与NodeJ一起读取的.json文件。 These files contain a date, a title and the content. 这些文件包含日期,标题和内容。

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

As you can see the date got the wrong format, it's the german date format. 如您所见,日期格式错误,这是德语日期格式。 When reading the directory I want to sort the files by their date property. 读取目录时,我想按文件的date属性对其进行排序。

Currently I just read the files and try to compare the date property 目前,我只是阅读文件并尝试比较date属性

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

Do I have to convert the date to a valid JavaScript date format first? 我是否必须先将日期转换为有效的JavaScript日期格式?

You could create an ISO 8601 compliant date and use the string for compairing. 您可以创建一个符合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); 

Try the following: 请尝试以下操作:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM