I have an array:
var array = [{
"date": "2022-09-08T04:00:00.000Z",
"value": "1.70",
},
{
"date": "2022-08-24T04:00:00.000Z",
"value": "1.20",
},
{
"date": "2022-08-02T04:00:00.000Z",
"value": "0.03",
},
{
"date": "2022-04-15T04:00:00.000Z",
"value": "1.20",
},
{
"date": "2022-04-10T04:00:00.000Z",
"value": "1.32",
},
{
"date": "2022-03-10T04:00:00.000Z",
"value": "1.50",
}
]
I am trying to filter the array by passing a selectedMonth value as follows:
public filterByMonth(
rates: Row[],
selectedMonth: Date
): Row[] {
return rates ? .filter(
(d) =>
d.date ? .getMonth() === selectedMonth? .getMonth() &&
d.date ? .getFullYear() === selectedMonth? .getFullYear()
);
}
The above snippet gives me the result I need. But, if the selected month doesn't have any value the array should return the value in the array that is less than selectedMonth.
Example: If selected month is August(08): the result is as follows:
array = [{
"date": "2022-08-24T04:00:00.000Z",
"value": "1.20",
},
{
"date": "2022-08-02T04:00:00.000Z",
"value": "0.03",
}]
If the selected month is July, I get an empty array. But, I want it to find values less than the selected month. In this case, it is April.
Expected Result:
array = [{
"date": "2022-04-15T04:00:00.000Z",
"value": "1.20",
},
{
"date": "2022-04-10T04:00:00.000Z",
"value": "1.32",
}]
Any idea how can I do that?