如何在 Javascript 中按日期对字段进行排序?

How to sort fields by date in Javascript?

我需要一些帮助来了解如何按以秒为单位的日期对这些数组进行排序,然后使用 .toDate 函数将其转换为日期。

const todoList = document.querySelector('.upcoming ul');
            const generateTemplate = (todo, date) => {
                const html = `<h5 style="padding-top: 5px; font-weight: 375; margin-top: auto;">${date}</h5><li>
                ${todo} 
                </li>`
                todoList.innerHTML += html;
            };

            let events = [];


            db.collection("Users").doc(user.uid).get().then((doc) => {
                var gid = doc.get("group");

                db.collection("Groups").doc(gid).get()
                    .then((document) => {
                        var fields = Object.keys(document.data());
                        var dates = Object.values(document.data());
                        console.log(fields);
                        console.log(dates);

                        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

                        fields.forEach(field => {
                            var date = document.get(field).toDate().toLocaleDateString('de-DE', options)
                            var now = new Date();

                            if (document.get(field).toDate() < now) {
                                var path = db.collection("Groups").doc(gid);
                                path.update({
                                    [field]: firebase.firestore.FieldValue.delete()
                                });
                            }
                            generateTemplate(field, date);
                        });
                    });


            });

我不确定如何解决这个问题,因为我正在使用 forEach 循环将所有 innerHTML 添加到列表中。

This is the list and the outputs for the fields and the dates

如果您需要任何进一步的信息,请回复。我对 Whosebug 和整个编程社区还是很陌生,因为我才 14 岁。

感谢您的帮助!

您可以在映射字段之前使用数组排序,如下所示:

db.collection("Groups")
  .doc(gid)
  .get()
  .then((document) => {
    var fields = Object.keys(document.data());
    var dates = Object.values(document.data());
    console.log(fields);
    console.log(dates);

    const options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    };

    fields
      .sort(function (a, b) {

        return document
          .get(b).seconds - document
          .get(a).seconds;
      })
      .map((field) => {
        var date = document
          .get(field)
          .toDate()
          .toLocaleDateString("de-DE", options);
        var now = new Date();

        if (document.get(field).toDate() < now) {
          var path = db.collection("Groups").doc(gid);
          path.update({
            [field]: firebase.firestore.FieldValue.delete(),
          });
        }
        generateTemplate(field, date);
      });
  });