How to filter an array and get the values by recent month in Angular?

Viewed 37

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?

1 Answers

You can do this using a recursive call by calling the same filterByMonth function with month - 1 until you find a value. Also add a termination condition for the year. Ex:- 2020

sample pseudo code for the function

public filterByMonth(
  rates: Row[],
  selectedMonth: Date
): Row[] {

  // termination condition 
      // termination condition is year 2020
    if(selectedMonth.getFullYear() === 2020){
      return [];
    }

  const filteredRates =  rates ? .filter(
    (d) =>
    d.date ? .getMonth() === selectedMonth? .getMonth() &&
    d.date ? .getFullYear() === selectedMonth? .getFullYear()
  );

  if(filteredRates.length === 0){

      let month = selectedMonth.getMonth();
      let year = selectedMonth.getMonth();
      if(month === 0){
        month = 11;
        year = year - 1;
      } else {
        month = month - 1
      }
      return this.filterByMonth(rates, new Date(selectedMonth.getFullYear(), selectedMonth.getMonth() - 1));
    } else {
      return filteredRates;
    }
  }
}

Also find the stackblitz here

Related