Structuring an array method in Vue.js project

Viewed 130

I have a method in Vue.js to filter a set of data to find any objects with a null value, then find the most recent of these.

At the moment there is a function that does this in reverse - finds the most recent record from an array and then checks if an object is null.

This is the data we are working with:

const contacts = [
    {
        "contactNumber": 429295,
        "startDate": "2015-01-01T00:00:00.000Z",
        "endDate": null,
    },{
        "contactNumber": 429295,
        "startDate": "2008-06-29T14:00:00.000Z",
        "endDate": "2015-02-27T13:00:00.000Z",
    },{
        "contactNumber": 429295,
        "startDate": "2008-06-29T14:00:00.000Z",
        "endDate": null,
    },{
        "contactNumber": 429295,
        "startDate": "2008-06-29T14:00:00.000Z",
        "endDate": "2015-02-27T13:00:00.000Z",
    },{
        "contactNumber": 429295,
    "startDate": "2015-01-01T00:00:00.000Z",
        "endDate": "2015-02-27T13:00:00.000Z",
    },{
        "contactNumber": 429295,
    "startDate": "2015-01-01T00:00:00.000Z",
        "endDate": "2015-02-27T13:00:00.000Z",
    }
]

This is the method to check for most recent contact startDate, and then checks if the endDate of this startDate is null, this gets mostRecent.

methods: {
    filterMostRecentActive(arr, startProp, endProp) {
      if (arr) {
        let mostRecent = this.filterMostRecentObj(arr, startProp);
        if (mostRecent[endProp] == null) {
          return mostRecent;
        } else {
          return false;
        }
      }
    },
    filterMostRecentDate(arr, prop) {
      if (arr) {
        return new Date(
          Math.max.apply(
            null,
            arr.map(item => {
              return new Date(item[prop]);
            })
          )
        );
      }
    },
    filterMostRecentObj(arr, prop) {
      if (arr) {
        return arr.filter(item => {
          let date = new Date(item[prop]);
          let mostRecent = this.filterMostRecentDate(arr, prop).getTime();
          return date.getTime() == mostRecent;
        })[0];
      }
    },
   } 

I need to reverse this process and change the method so that it gets one or many contacts with a null endDate, then finds the the contact with recent start date from this array, to get nullEndDateMostRecent.

I am not sure how to structure this. Can anyone help steer me in the right direction?

1 Answers

This should do the job:

 contacts
    .filter(contact => contact.endDate === null)
    .sort((a, b) => new Date(b.startDate) - new Date(a.startDate))[0] || null
Related