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?

1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I think you have this the other way round. From your console.log maxDate comes first and 10-12-2018 is not the maximum date right?
@user2320476 yes, i fixed the answer
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.