Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count elements by date month and year

I have a function that can count the total number of occurences for elements. However, i would like to have a function that can count the elements by date, month or year.

data.js

[{
  _id:"1",
  "Name":"John",
  "Booked":"Executive"
  "date": 2023-03-02T18:15:26.723+00:00
   },

   {
  _id:"2",
  "Name":"Peter",
  "Booked":"Economy",
  "date": 2023-03-19T19:15:26.723+00:00
   },

  {
  _id:"3",
  "Name":"Wade",
  "Booked":"Economy",
  "date": 2024-04-19T19:15:26.723+00:00
   },
   {
  _id:"4",
  "Name":"Mary",
  "Booked":"Economy",
  "date": 2024-04-20T19:15:26.723+00:00
   }]
 

countfunction.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      statusCounter(inputs) {
          let counter = 0;
          for (const input of inputs) {
            if (input.Booked === 'Economy') counter += 1;
          }
          return counter;
        }   

I would like to be able to get a function that can calculate the total occurence of element booked "Economy" by date, month, year. Thanks in advance.

>Solution :

You can use the setState if you are working with react

import {useState} form "react";

const Component = () => {
  const [count, setCount] = useState(0);

  statusCounter(inputs) {
    const filteredByBooked = inputs.filter(input => input.Booked === "Economy");
    setCount(filteredByBooked.length); // will count the number of elements with booked = "Economy"
  }
}

If you want to filter by a certain year or by month you can follow a similar approach where instead of using input.Booked you go for input.date. you will probably have to translate the timestamp into a string and use a Date() object to be able to access the month or year.

  statusCounter(inputs) {
      const filteredByMonth = inputs.filter(input => new Date(input.date.toString()).getMonth() === 3); //months go from 0 to 11, so this is to check for April.
      setCount(filteredByMonth.length)
  }

This should return a count based on a certain month (in example: April (or month number 3, since January starts at 0)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading