How to filter an array based on Month comparison and get Max Date() in Angular?

Viewed 47

I have an array of objects with a date value. I want to filter the array based on the selectedDate and get the Max date in the list of dates. In the below code, I am filtering the array based on the month. Here I get 3 values after filtering, now I want to compare those values and get the MAX Date() value.

How can I do that in Angular or ES6 way?

let selectedDate = new Date();
let array = [{
    "date": "2022-08-30T23:00:00Z",
    "value": "4.0"
  },
  {
    "date": "2022-08-28T23:00:00Z",
    "value": "8.0"
  },
  {
    "date": "2022-08-25T23:00:00Z",
    "value": "2.0"
  },
  {
    "date": "2022-07-25T23:00:00Z",
    "value": "2.0"
  }
];

let x = array.filter(d =>
  new Date(d.date).getMonth() === selectedDate.getMonth() - 1
)
console.log(x)

Expected Output:
{
  "date": "2022-08-30T23:00:00Z",
  "value": "4.0"
}
3 Answers

let yourOutput = [
  {
    "date": "2022-08-30T23:00:00Z",
    "value": "4.0"
  },
  {
    "date": "2022-08-28T23:00:00Z",
    "value": "8.0"
  },
  {
    "date": "2022-08-25T23:00:00Z",
    "value": "2.0"
  }
];
//Sort by Date
yourOutput.sort((a, b) => new Date(a) > new Date(b));
//Get First Elem
if(yourOutput.length > 0) {
    console.log(yourOutput[0])
}

You need to filter not only by month, but also by year. Please do not use new in the loop, if possible.

const array = [{"date": "2022-08-30T23:00:00Z","value": "4.0"},{"date": "2022-08-28T23:00:00Z","value": "8.0"},{"date": "2022-08-25T23:00:00Z","value": "2.0"},{"date": "2022-07-25T23:00:00Z","value": "2.0"}];

const selectedDate = '2022-09-01T06:08:58.695Z' // new Date().toISOString();
const getYearMonth = (isoDateTime) => isoDateTime.slice(0,7)

const getMax = (data, targetDate) => {
  const targetYearMonth = getYearMonth(targetDate);
  const filtered = data.filter(({ date }) => getYearMonth(date) === targetYearMonth);
  if (filtered.length === 0) return null;
  if (filtered.length === 1) return filtered.at(0);
  
  return filtered.reduce((max, cur) => max.date.localeCompare(cur.date) < 0 ? cur : max)
};

console.log(getMax(array, '2022-07-01T06:08:58.695Z'))
console.log(getMax(array, '2022-08-01T06:08:58.695Z'))
console.log(getMax(array, '2022-09-01T06:08:58.695Z'))
.as-console-wrapper { max-height: 100% !important; top: 0 }

I think you can use reduce function afterfilter to get the max.

Assuming we have 2 variables, selectedDate and array:

let max = array
    .filter(d =>
      new Date(d.date).getMonth() === selectedDate.getMonth() - 1
    )
    .reduce((max, current) => {
        if (!max) return current;
        let maxDate = new Date(max.date);
        let currentDate = new Date(current.date);
        return maxDate > currentDate? max: current;
    }, null);
Related