【问题标题】:How to find the newest date with reduce in javascript如何在javascript中使用reduce查找最新日期
【发布时间】:2022-11-28 21:34:02
【问题描述】:

我有 items 对象如下。我想找到created 是最新的对象。

const items = [
        { id: 'djw8701', created: '2019-10-05T11:06:20.208Z', url: 'url1' },
        { id: 'djw8702', created: '2019-10-15T12:06:21.208Z', url: 'url2' },
        { id: 'djw8703', created: '2019-10-20T13:06:22.208Z', url: 'url3' }
      ]

我想比较数组中的对象并获得一个具有最新日期的对象items[2]

我下面的方法什么都不返回。

items?.reduce((curr, acc) => {
          if (curr.created < acc.created) {
            return { ...acc };
          }
        })

【问题讨论】:

  • 当 reduce 为 falsy 时,reduce 返回 undefined

标签: javascript


【解决方案1】:

首先,您需要将其转换为new Date(),以便您可以比较它们。

const deliveries = [{ id: 'HgP6cJB03', deliveryDate: '2022-10-20T13:06:22.208Z', url: 'some link3' }, { id: 'HgP6cJB01', deliveryDate: '2022-10-05T11:06:20.208Z', url: 'some link1' }, { id: 'HgP6cJB02', deliveryDate: '2022-10-15T12:06:21.208Z', url: 'some link2' }, ]

//When curr is newest we retun {...curr} if it's not we just return current accumulator {...acc}
const newest = deliveries.reduce((acc, curr) => new Date(curr.deliveryDate) > new Date(acc.deliveryDate) ? {...curr} : {...acc});
console.log(newest);

【讨论】:

    【解决方案2】:

    当你做比较时,做类似的事情

    if (new Date(curr.deliveryDate) < new Date(acc.deliveryDate))
    

    【讨论】:

      【解决方案3】:

      如果交货日期始终采用 ISO-8601 格式,那么您可以像这样简单地进行操作:

      const deliveries = [
        { id: 'HgP6cJB01', deliveryDate: '2022-10-05T11:06:20.208Z', url: 'some link1' },
        { id: 'HgP6cJB02', deliveryDate: '2022-10-15T12:06:21.208Z', url: 'some link2' },
        { id: 'HgP6cJB03', deliveryDate: '2022-10-20T13:06:22.208Z', url: 'some link3' }
      ];
      
      const oldest = deliveries.reduce(
          (acc, curr) => acc.deliveryDate < curr.deliveryDate ? curr : acc
      );
      
      console.log(oldest);

      它返回对 deliveries 项的引用,因此修改它时要谨慎。如果您需要一个副本,那么您可以简单地解构 Array.reduce() 返回的值并将其重新组合成一个新对象:

      const oldest = { ... deliveries.reduce() }
      

      无需在Array.reduce() 的每次迭代中创建副本;回调不会修改它使用的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2012-08-01
        • 1970-01-01
        • 2022-11-01
        相关资源
        最近更新 更多