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
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)