0

I have some .json files to read with NodeJs. 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.

Currently I just read the files and try to compare the date property

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?

1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

You could create an ISO 8601 compliant date and use the string for compairing.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.