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

Time:09-01

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"
}

CodePudding user response:

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

CodePudding user response:

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