Sorting through an array of timestamps to specifically filter out entries from 'last week', 'last month', and 'last year'

Currently, I am working with an array of timestamps and respective values. For each timestamp, I am converting it into a date format. There is a function in place that displays the dates from oldest to newest. My goal is to calculate time frames such as last week, last month, and last year based on today's date.

const myData = [
  {timestamp: 1382086394000, value: 200},
  {timestamp: 1382086394001, value: 200},
  {timestamp: 1232131231232, value: 300},
  {timestamp: 2131231241212, value: 400},
  {timestamp: 1234124124112, value: 285},
  {timestamp: 1251251251251, value: 123},
  {timestamp: 1241241241241, value: 512},
  {timestamp: 1241241241241, value: 124},
  {timestamp: 2312312123121, value: 600},
];

This represents how the current array appears after converting the timestamps to actual dates. It's important to note that this conversion has already been done.

Answer №1

Utilizing the functions for manipulating dates in Moment.js such as add or subtract can help with this task.

let timestamp = 1382086394000; 
console.log(moment(timestamp )) // Moment<2013-10-18T08:53:14+00:00>

// calculating the date one week after the provided timestamp
console.log(moment(timestamp ).add(1, 'w')) // Moment<2013-10-25T08:53:14+00:00>

You can use similar methods to find the date from last week, month, and year by subtracting accordingly. Moment.js handles all possible scenarios that may arise.

Answer №2

To determine the previous year (assuming a full year from Jan 1st to Dec 31st 2020 if the current year is 2021), last month (assuming a complete month from Jan 1st to Jan 31st if the current date is February), and the past week (including the last 7 days, today included), you can follow these steps.

I prefer using a semi-open interval approach (where the end of the period is not inclusive) to avoid creating timestamps like 23:59:59.999. This means you would need to compare with < for the end point.

By utilizing getMonth()-1 or getDate()-6, you tap into the internal calculations within the date object constructor. For example, executing new Date(2021, 0, -3) will yield December 28th, 2020.

let today = new Date();
console.log(today.toLocaleString());

let lastYearStart = new Date(today.getFullYear()-1, 0, 1);
let lastYearEnd = new Date(today.getFullYear(), 0, 1);

console.log(lastYearStart.toLocaleString());
console.log(lastYearEnd.toLocaleString());


let lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 1);
let lastMonthStart = new Date(lastMonthEnd.getFullYear(), lastMonthEnd.getMonth()-1, 1);

console.log(lastMonthStart.toLocaleString());
console.log(lastMonthEnd.toLocaleString());

let lastWeekStart = new Date(today.getFullYear(), today.getMonth(), today.getDate()-6);
let lastWeekEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate()+1);

console.log(lastWeekStart.toLocaleString());
console.log(lastWeekEnd.toLocaleString());

const mydata = [
  {timestamp: 1382086394000, value: 200},
  {timestamp: 1382086394001, value: 200},
  {timestamp: 1232131231232, value: 300},
  {timestamp: 2131231241212, value: 400},
  {timestamp: 1234124124112, value: 285},
  {timestamp: 1251251251251, value: 123},
  {timestamp: 1241241241241, value: 512},
  {timestamp: 1241241241241, value: 124},
  {timestamp: 2312312123121, value: 600},
];

for (let d of mydata) {
  if (d.timestamp >= lastWeekStart.getTime() && d.timestamp < lastWeekEnd.getTime())
    console.log("last week");
  else if (d.timestamp >= lastMonthStart.getTime() && d.timestamp < lastMonthEnd.getTime())
    console.log("last month");
  else if (d.timestamp >= lastYearStart.getTime() && d.timestamp < lastYearEnd.getTime())
    console.log("last year");
}

A particular timestamp may fall into all three categories, last week, last month, and last year, depending on the current date. Adjust the classification as needed (use only if instead of else if) if a timestamp could be classified under multiple categories.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for automating redirection to error pages within Nuxt

Currently using Nuxt 2 with some customizations. All application state management is handled within Vuex modules, totaling 32 for this complex app. When fetching data, a call to fetch is made from the view, triggering a mapped Vuex action that wraps the A ...

Combine multiple Line objects in THREE.js using GeometryUtils.merge

Is there a way to improve performance by merging multiple Line objects into a single geometry using GeometryUtils.merge? It doesn't seem to work as expected with Line objects. Is it necessary to redefine the concept of a line to achieve this optimizat ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

Problem encountered while converting a string to an unsigned long integer

Having an issue with converting a char string array to an unsigned long. Here's the input for executeCommand(): 0001000118218;326 This is what I receive back: Received command: 0001000118218;326 Transmit code: 1821 Transmit period: 32 The droppe ...

Contrast the NSManagedObject Array with an Array containing a different "Object" Type in Swift 2

I need a reliable method to compare an array of NSManagedObjects with a similar array of objects/structs extracted from a file. Both sets contain items with matching attributes, such as the core data "Item" entity mirroring the content of a file "Item". He ...

Converting JSON data into a PHP array is not within my capabilities

Can anyone help me figure out why I'm having trouble converting this JSON data into a PHP array? {"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},&quo ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

I am experiencing an issue where my JavaScript code does not redirect users to the next page even

I'm experiencing an issue with this code where it opens another webpage while leaving the login screen active. I've tried multiple ways to redirect it, such as window.location.href and window.location.replace, but nothing seems to be working. Ide ...

What is the best way to assign a Vue property the value of a stringified element attribute?

Apologies for the question that may seem silly. Here is the code snippet I am currently working with: var app = new Vue({ el: '#app', data: { words: [] }, created() { let something = document.getElementById('word_data' ...

Similar to tabpanel's ._hide() function, how can this be implemented in C#?

Even though I feel like I've tackled this issue in the past, I can't seem to locate a resolution anywhere... In my situation, there are 3 tabs within an ajax TabContainer and two CheckBoxes located outside of it. All 3 tabs are visible unless bo ...

Excessive notification events are currently causing a blockage in the Angular app

Currently, I am utilizing Angular 7 in combination with SignalR on the backend for push notifications. At certain times, an overwhelming amount of notifications flood in, causing my application to become completely unresponsive. The SignalR service compon ...

PHP: Calculating the frequency of identical values in a multi-dimensional array

I need to tally up identical values within the innermost layer of a multidimensional array: Array ( [svote001] => Array ( [0] => 006 [1] => 006 [2] => 007 ) [svote002] => Array ( [0] => 000 ...

What is the reason for Julia's inability to identify the type of an array being passed as a function argument, instead categorizing it as Any?

Currently, I am in the process of defining a function in Julia that takes in a vector, specifically Vector{Complex128}. However, upon inspecting the output of @code_warntype, I noticed that the variable type is identified as Any. This could potentially imp ...

Sorting through an array of dates in milliseconds, extracting objects with subcategories, and dynamically displaying them on the calendar based on the specific date

So I am currently working with a JSON object containing an array of objects structured like this: [ { "id": 0, "name": "Sophia Mason", "availability": [ { "date": 1522216800000, "times": ["9:00 am", "2:3 ...

Traverse through a numpy array in order to populate a python list

Currently, I am cycling through a numpy array to implement a function on each element and store the updated value in a list to preserve the initial data. Unfortunately, the process is quite slow. Is there a more efficient approach to achieve this task wi ...

Ensure that all characters in a string are contained within a specified array of strings using Java

I'm in the process of developing a method that scans each character in userInput to determine if it exists within operatorsAndOperands. The challenge I'm facing is that tempbool consistently returns false for all values. import java.util.*; pub ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

When is the best time to assign properties to mobx domain objects?

When it comes to tackling a specific problem in my react/mobx application, I'm facing challenges finding an optimal solution. Imagine having multiple boxes that need to be positioned on the screen based on various factors such as interdependency betwe ...