2

I have an array object that has a date field like this

    settledDate: "12-19-2018"
    settledDate: "12-12-2018"
    settledDate: "10-19-2018"
    settledDate: "10-12-2018"

I will like to determine the minimum and maximum date in this array.

I tried this but no luck

    const maxDate = new Date(Math.max.apply(null, this.props.form.details.bulkDetailsInvoices.settledDate)); 

    const minDate = new Date(Math.min.apply(null, this.props.form.details.bulkDetailsInvoices.settledDate)); 

Any ideas on what I can do to make this work?

Baba
  • 2,059
  • 8
  • 48
  • 81
  • 2
    Possible duplicate of [Min/Max of dates in an array?](https://stackoverflow.com/questions/7143399/min-max-of-dates-in-an-array) – Tom Faltesek Sep 30 '19 at 20:14

2 Answers2

2

Sort the array by date and pick the first and the last ones :

const dates = [
  { settledDate: "12-19-2018" },
  { settledDate: "12-12-2018" },
  { settledDate: "10-19-2018" },
  { settledDate: "10-12-2018" }
];

const sorted = dates.sort((a, b) => new Date(a.settledDate) - new Date(b.settledDate));

const minDate = sorted[0];
const maxDate = sorted.reverse()[0];

console.log('maxDate : ', maxDate.settledDate);
console.log('minDate : ', minDate.settledDate);
Taki
  • 17,320
  • 4
  • 26
  • 47
1

Here is a linear time O(n) solution. (I didn't find any linear time solution in linked duplicate question.)

const dates = [
  { settledDate: "12-19-2018" },
  { settledDate: "12-12-2018" },
  { settledDate: "10-19-2018" },
  { settledDate: "10-12-2018" }
];

let maxDate = dates[0];
let minDate = dates[0];

dates.forEach(item => {
 if (new Date(item.settledDate) < new Date(minDate.settledDate)) {
   minDate = item;
 }
 
 if (new Date(item.settledDate) > new Date(minDate.settledDate)) {
   maxDate = item;
 }
});

console.log("minDate:", minDate);
console.log("maxDate:", maxDate);
Nikhil
  • 6,493
  • 10
  • 31
  • 68