Question3r
Question3r

Reputation: 3802

sort array by foreign date property in JavaScript

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?

Upvotes: 0

Views: 45

Answers (2)

amrender singh
amrender singh

Reputation: 8239

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

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

Upvotes: 1

Related Questions