我需要比较给定数组元素的时间戳,并根据 JavaScript 中的比较将这些元素推送到新数组

i need to compare timestamps of given array elements and push those elements to new arrays based on that comparison in JavaScript

我有一个数组,其中包含每个对象的时间戳 我需要检查每个对象的时间戳并将整个对象推送到相应的数组。 我已经尝试了以下方法并且它有效但问题是我有大量数据并且该过程需要很多时间才能完成:

      const thisMonthArray = []
      const thisYearArray = []
      const thisQuarterArray = []

      data = [
        {id:'1',createdOn:1631166889,items:[{itemname:'name1',details:'details1'}]},
        {id:'2',createdOn:1625291689,items:[{itemname:'name2',details:'details2'}]},
        {id:'3',createdOn:1612335289,items:[{itemname:'name3',details:'details3'}]}
      ]


      const fillTheArrays = (element) => {
        // element timestamp
        const timestamp = element.createdOn
        const milliseconds = timestamp * 1000
        const dateObject = new Date(milliseconds)
        let createTime = dateObject.toLocaleString()
        createTime = createTime.substr(0, createTime.indexOf(','))
        const createyear = createTime.substr(createTime.lastIndexOf('/') + 1)
        const createmonth = createTime.substr(0, createTime.indexOf('/'))

        // current timestamp
        const currenstamp = Date.now()
        const currentDateObj = new Date(currenstamp)
        let currentDate = currentDateObj.toLocaleString()
        currentDate = currentDate.substr(0, currentDate.indexOf(','))
        const currentyear = currentDate.substr(currentDate.lastIndexOf('/') + 1)
        const currentmonth = currentDate.substr(0, currentDate.indexOf('/'))

        if (createyear === currentyear) {
          if (createmonth === currentmonth) {
            thisMonthArray.push(element)
          } else if (createmonth >= (currentmonth - 3)) {
            thisQuarterArray.push(element)
          } else {
            thisYearArray.push(element)
          }
        }
      }
    
      data.forEach(element => fillTheArrays (element))
        let results = { cratedOn: Date.now(), thisMonth: thisMonthArray, thisQuarter: thisQuarterArray, thisYear: thisYearArray }

        console.log(results)

Odeh,你好吗?

根据您展示的内容,我相信您可以简化一些代码。您是否尝试过使用 Date 对象实例函数而不是对某些行为进行硬编码,例如:

// instead of getting the year by cutting the createTime string variable, you could simply compare both date objects:

dateObject.getFullYear() === currentDateObject.getFullYear()

你可以阅读更多here

我们可以使用 intervals 对象来定义我们感兴趣的间隔,为每个间隔添加 startend 属性。

一旦我们定义了这个,我们就可以创建我们的 fillTheArrays 函数,它将遍历每个间隔并使用 Array.reduce()Array.filter() 来获取每个间隔的数据项。如果 createdOn 属性 大于或等于间隔开始且小于或等于间隔结束,则日期项被视为间隔的一部分。

通过避免调用 new Date() 和 String.substr() 等,我们将使用这种方法显着提高性能。

const year = new Date().getFullYear();
const month = new Date().getMonth();
const quarter = Math.ceil((month + 1) / 3);

const data = [
    {id:'1',createdOn:1631166889,items:[{itemname:'name1',details:'details1'}]},
    {id:'2',createdOn:1625291689,items:[{itemname:'name2',details:'details2'}]},
    {id:'3',createdOn:1612335289,items:[{itemname:'name3',details:'details3'}]}
];
      
const intervals = {
    thisYear: { start: new Date(year, 0, 1, 0, 0, 0).getTime(), end: new Date(year, (quarter - 1) * 3, 0, 23, 59, 59).getTime() },
    thisQuarter: { start: new Date(year, (quarter - 1) * 3, 1, 0, 0, 0).getTime(), end: new Date(year, quarter * 3, 0, 23, 59, 59).getTime() },
    thisMonth: { start: new Date(year, month, 1, 0, 0, 0).getTime(), end: new Date(year, month + 1, 0, 23, 59, 59).getTime() }
}

console.log(`Interval\tStart\t\t\tEnd`);
Object.entries(intervals).forEach(([key,value]) => { 
    console.log(`${key}\t${new Date(value.start).toLocaleString('sv')}\t${new Date(value.end).toLocaleString('sv')}`);
})

function fillTheArrays(intervals, data) {
     // Start by filtering by the minimum start and maximum end date of our intervals.
    const minStart = Math.min(...Object.values(intervals).map(({start}) => start));
    const maxEnd = Math.max(...Object.values(intervals).map(({end}) => end));
    const inRangeData = data.filter(entry => (entry.createdOn * 1000 >= minStart) && (entry.createdOn * 1000 <= maxEnd));
    
    return Object.entries(intervals).reduce((acc, [key, value]) => {
        acc[key] = inRangeData.filter(entry => {
            return (entry.createdOn * 1000 >= value.start) 
                && (entry.createdOn * 1000 <= value.end)
        });
        return acc;
    }, { createdOn: Date.now() })
}

console.log('\nResult:', JSON.stringify(fillTheArrays(intervals, data), null, 2))