【问题标题】:Get 5 oldest Objects from an array从数组中获取 5 个最旧的对象
【发布时间】:2022-02-19 13:51:29
【问题描述】:

我有一个形式的对象数组:

{productID: '15', name: 'Pepsi', category: 'food/beverages', dateAdded: '2015-12-21T17:42:34Z'}

我想通过比较 dateAdded 字符串来找到 5 个最旧的项目。我尝试了一些低效的循环并以reduce() 失败,但我觉得有一种更有效的方法。如何累积最旧的 5 个项目?

【问题讨论】:

  • 你提到efficent way你的阵列有多大?

标签: javascript arrays datetime


【解决方案1】:

一个简单的排序/切片就可以了——日期的格式意味着你可以在你的排序调用中做一个localeCompare ...`

const array = [
    {productID: '15',name: 'Pepsi',category: 'food/beverages',dateAdded: '2015-12-21T17:42:34Z'},
    {productID: '13',name: 'Coke',category: 'food/beverages',dateAdded: '2015-12-20T17:42:34Z'}
];
const top5 = array
    .sort(({dateAdded: a}, {dateAdded: b}) => a.localeCompare(b))
    .slice(0, 5);
console.log(top5);

【讨论】:

  • 哇,我想多了,完全忽略了排序。感谢您的回答!
【解决方案2】:

您可以按datetime 排序,如下所示。

array.sort((firstEl, secondEl) => 
    new Date(firstEl.dateAdded).getTime() - new Date(secondEl.dateAdded).getTime())
    .slice(0, 5);

 const array = [
      { productID: '0', name: 'Pepsi', category: 'food/beverages', dateAdded: '2015-12-21T17:42:34Z' },
      { productID: '1', name: 'Coke', category: 'food/beverages', dateAdded: '2015-10-20T17:42:34Z' },
      { productID: '2', name: 'Coke', category: 'food/beverages', dateAdded: '2015-11-20T17:42:34Z' },
      { productID: '3', name: 'Coke', category: 'food/beverages', dateAdded: '2015-08-20T17:42:34Z' },
      { productID: '4', name: 'Coke', category: 'food/beverages', dateAdded: '2015-01-20T17:42:34Z' },
      { productID: '5', name: 'Coke', category: 'food/beverages', dateAdded: '2015-03-20T17:42:34Z' },
      { productID: '6', name: 'Coke', category: 'food/beverages', dateAdded: '2016-10-20T17:42:34Z' },
      { productID: '7', name: 'Coke', category: 'food/beverages', dateAdded: '2017-10-20T17:42:34Z' },
    ];
    
const newArr = array.sort((firstEl, secondEl) => new Date(firstEl.dateAdded).getTime() - new Date(secondEl.dateAdded).getTime()).slice(0, 5);
    
console.log(newArr);

【讨论】:

    【解决方案3】:

    dateAdded对项目进行排序,然后取前5名,应该是最旧的

    【讨论】:

      【解决方案4】:

      对数组进行排序的解决方案可能会修改数组中元素的顺序。一种非变异方法是获取要排序的值和相关索引,这样您就可以在不修改源数组的情况下获取所需的元素,例如

      // To generate random data
      function genRandomData(num = 10) {
        let result = [];
        for (let i=0; i<num; i++) {
          result.push(
            {productID: i,
             dateAdded: new Date(Date.now() + (Math.random() - 0.5) * 1e10).toISOString()}
          );
        }
        return result;
      }
      
      // Return n oldest entries in data
      function getOldest(n, data) {
        let indexes = data.map((obj, i) =>
          ({index:i, date: obj.dateAdded})
        ).sort( // Oldest first
          (a, b) => b.date.localeCompare(a.date)
        );
        return indexes.slice(0,n).map(obj => data[obj.index]);
      }
      
      // Random data from genRandomData()
      let data = [
        {
          "productID": 0,
          "dateAdded": "2022-01-23T17:41:20.135Z"
        },
        {
          "productID": 1,
          "dateAdded": "2022-01-13T14:35:25.296Z"
        },
        {
          "productID": 2,
          "dateAdded": "2022-01-14T20:39:27.210Z"
        },
        {
          "productID": 3,
          "dateAdded": "2022-01-30T16:50:00.163Z"
        },
        {
          "productID": 4,
          "dateAdded": "2022-02-28T22:04:53.106Z"
        },
        {
          "productID": 5,
          "dateAdded": "2022-01-12T03:08:29.874Z"
        },
        {
          "productID": 6,
          "dateAdded": "2022-02-18T07:13:25.202Z"
        },
        {
          "productID": 7,
          "dateAdded": "2022-04-10T17:35:30.277Z"
        },
        {
          "productID": 8,
          "dateAdded": "2022-01-29T11:43:22.832Z"
        },
        {
          "productID": 9,
          "dateAdded": "2022-03-18T06:29:28.833Z"
        }
      ];
      
      // Oldest 3 elements of data
      console.log(getOldest(3, data))

      请注意,原始数组中的对象被返回的数组引用,因此修改它们也会修改原始数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        相关资源
        最近更新 更多