如何使用 find 函数查找当前周数

How to find the current number of the week with find function

我有门票对象,每张门票都有自己的日期:

tickets: [
           {
             id: 0,
             time: "09:45",
             date: new Date("2021-01-01"),
             name: "Swimming in the hillside pond",
           },
           {
             id: 1,
             time: "09:45",
             date: new Date("2021-01-08"),
             name: "Swimming in the hillside pond",
           },
         ],

所以我想做的是找到每张票的周数,而且周数是否与当前的不同。例如,如果票日期是 01.01 2021,周数应该是 1,如果是 08.01.2021,应该是 2。所以如果我有 3 张票,如果这些票的日期是 [01.01.2021, 08.01.2021, 09.01.2021],我想要一个像 [1,2].

这样的数组

为此,我创建了函数:

currentNumberOfWeek(tickets) {
  return tickets.find((ticket, result) => {
    const oneJan = new Date(ticket.date.getFullYear(), 0, 1);
    const numberOfDays = Math.floor((ticket.date - oneJan) / (24 * 60 * 60 * 1000));
    result = Math.ceil((ticket.date.getDay() + 1 + numberOfDays) / 7);
    console.log(result);
    return result;
  });
},

但首先,它 returns 票不是结果,而且在控制台中它没有显示正确的周数。

你能看看吗? 谢谢...

如果您只想查找机票的周数

const tickets = [
    {
        id: 0,
        time: "09:45",
        date: new Date("2021-01-01"),
        name: "Swimming in the hillside pond",
    },
    {
        id: 1,
        time: "09:45",
        date: new Date("2021-01-08"),
        name: "Swimming in the hillside pond",
    },
    {
        id: 1,
        time: "09:45",
        date: new Date("2021-01-12"),
        name: "Swimming in the hillside pond",
    },
]


let result = new Set()

function currentNumberOfWeek(arr) {
  arr.forEach(t => {
    let res = getWeekNr(t.date)
    result.add(res)
  })
}

function getWeekNr (date) {
  const oneJan = new Date(date.getFullYear(), 0, 1);
  const numberOfDays = Math.floor((date - oneJan) / (24 * 60 * 60 * 1000));
  let weekNr = Math.ceil((date.getDay() + 1 + numberOfDays) / 7);
  return weekNr;
}
currentNumberOfWeek(tickets)
console.log([...result]);