Home > OS >  React Filter array of objects by date within a certain range using buttons, moment js
React Filter array of objects by date within a certain range using buttons, moment js

Time:01-25

So i have an array objects with dates and scores. I would like to create an onclick handler that updates data everytime i click one of the 4 buttons. My 4 buttons represent 3 months, 6 months, 12 months and reset. I would like to filter this data from todays date to "blank" months ago. I am thinking of using moment and here is what i have so far. Just not sure if im going the right direction or how to solve this issue.

const threeMonths = moment().startOf('day').subtract(3, 'month').format('YYYY-MM-DD');
const sixMonths = moment().startOf('day').subtract(6, 'month').format('YYYY-MM-DD');
const twelveMonths = moment().startOf('day').subtract(12, 'month').format('YYYY-MM-DD');

Example: Clicking the 3 months button I would like to filter this data from todays date to 3 months ago

Starting:

 Data = [ 
    {date: '2023-01-22', score: 57.675},
    {date: '2022-11-05', score: 60.675},
    {date: '2022-12-11', score: 78.675},
    {date: '2022-08-26', score: 81.675}
    ]

<Button onclick= {} > 3 months </Button>

After 3 month button click: Only dates within 3 months remain

Data = [ 
    {date: '2023-01-22', score: 57.675},
    {date: '2022-11-05', score: 60.675},
    {date: '2022-12-11', score: 78.675},
    ]

CodePudding user response:

Codesandbox

store your data in state and on click of button use javascript filter method to filter the array and update state.

  • Related