根据最旧到最新的日期将对象插入到数组中

问题描述 投票:0回答:2

我是一个对象数组。每个对象都有一个date属性和一个字符串属性。我也有一个空数组。我无法弄清楚根据日期最新到最新推送字符串的逻辑。

     const oldToNew = []
     for (const baseId in results[key][test]) {
            // log the array of objects
            //example [{string: 'test', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-010T10:36:37.206000Z'}]
            console.log(results[key][test][baseId])
            results[key][test][baseId].forEach(element => {

            });
        }
     // I want the value to be [test, test1]
javascript arrays date javascript-objects
2个回答
1
投票

您需要使用sort对初始数组进行排序,然后使用map提取字符串

这样的事情:

array.sort((a, b) => a.date < b.date).map(el => el.string);

1
投票

使用Array.sort比较每个Object的date属性与之前的属性 - 然后使用Array.map返回所有项目的string属性的数组。

更新不需要parse日期时间戳。

const items = [{string: 'test4', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-10T10:36:37.206000Z'}, {string: 'test2', date: '2019-03-09T10:36:37.206000Z'}, {string: 'test3', date: '2019-03-07T10:36:37.206000Z'}]

const strings = items
  .sort((a, b) => b.date > a.date)
  .map(({ string }) => string)

console.log(strings)
© www.soinside.com 2019 - 2024. All rights reserved.