javascript - 检查对象中日期的顺序

标签 javascript arrays sorting

我试图确保对象中输入的日期顺序符合逻辑顺序。这是我的代码:

function checkDates(pet) {
        const dates = [
            pet.birthDate,
            pet.saleDate,
            pet.acquisitionDate,
            pet.deathDate
        ].filter( (date) => {
            // filter out undefined items
            return date;
        });

        // list of dates in their chronological order
        const sortedDates = dates.slice(0).sort();

        const inOrder = dates.every( (date, i) => {
            // check to make sure entered date is the same as the chronological date
            return date === sortedDates[i];
        });

        if (!inOrder) {
            throw new ValidationError('The dates are in an illogical order');
        }
    }

问题是 saleDate 和 AcquisitionDate 不需要按照该顺序(如日期数组中定义) - 它们只需要大于birthDate并小于deathDate即可。不同的日期不是必需的,例如,通过我的外观传递的宠物对象如下所示:

const pet = {
  name: "Sam",
  birthDate: "2017-01-01",
  acquisitionDate: "2017-02-01",
  saleDate: "2017-03-01"
}

进一步说明:如果存在,出生日期必须始终排在第一位,死亡日期必须始终排在最后。出售和收购必须在出生日期和死亡日期之间(如果存在),否则,无论出售发生在收购之前还是反之亦然。

最佳答案

您走在正确的道路上,但不一定需要排序:

function checkDates(pet) {
    const dates = [
        pet.birthDate,
        pet.saleDate,
        pet.acquisitionDate,
        pet.deathDate
    ].filter(date => date);

    const inOrder =
        (pet.birthDate ? dates.every(date => date >= pet.birthDate) : true) &&
        (pet.deathDate ? dates.every(date => date <= pet.deathDate) : true)

    if (!inOrder) {
        throw new ValidationError('The dates are in an illogical order');
    }
}

关于javascript - 检查对象中日期的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46697000/

相关文章:

javascript - 在 JavaScript/CoffeeScript 中确定一个数组是否包含另一个数组的内容

java - 如何对 Java ArrayList 进行降序排序?

c# - 使 C# ParallelEnumerable.OrderBy 稳定排序

javascript - 如何在页面上移动图像并使其实时保持位置?

Javascript 点击函数

javascript - Shiny未检测到shiny :inputchanged event

java - 使用 2 个条件对 Java 中的列表进行排序

javascript - 将 PHP echo 放入按钮的 insideHTML 中不起作用

c - 如何取消引用作为传递给函数的数组元素的指针

ios - 将字符串数组转换为连接字符串数组