Im trying to filter the directors $inactiveDirectors
who were active during the selected fromDate
and the toDate
.
Directors will be active from their effective date (director.effective_date
) to their resigned/removed date (director.release_date
). And if the user did not pick a toDate
it will be assumed to as the current date.
The function:
function loadDirectors() {
return {
fromDate: ""
, toDate: ""
, fromDateObj: null
, toDateObj: null
, directorsList: @json($inactiveDirectors)
, get filteredDirectors() {
if (this.fromDate === "") {
return this.directorsList;
}
this.fromDateObj = new Date(this.fromDate);
if (this.toDate === "") {
this.toDateObj = null;
} else {
this.toDateObj = new Date(this.toDate);
}
return this.directorsList.filter((director) => {
let effective_date_obj = new Date(director.effective_date);
let release_date = new Date(director.release_date);
if (this.fromDateObj.getTime() < effective_date_obj.getTime()) {
if (this.toDateObj) {
if (this.toDateObj.getTime() > release_date.getTime()) {
return director;
} else {
return director;
}
}
}
});
}
}
}
I've been trying to filter using Alpine.js with no luck yet. Appreciate if you could find a way to resolve this.
Thank you
CodePudding user response:
I resolved it. For your reference:
function loadDirectors() {
return {
fromDate: ""
, toDate: ""
, fromDateObj: null
, toDateObj: null
, directorsList: @json($inactiveDirectors)
, get filteredDirectors() {
if (this.fromDate === "" && this.toDate === "") {
return this.directorsList;
}
// if toDate not selected
if (this.toDate === "") {
this.toDateObj = null;
} else {
this.toDateObj = new Date(this.toDate);
}
// if fromDate not selected
if (this.fromDate === "") {
this.fromDateObj = null;
} else {
this.fromDateObj = new Date(this.fromDate);
}
return this.directorsList.filter((director) => {
// director effective date object
let effectiveDate = director.effective_date;
const eArray = effectiveDate.split("/");
let effectiveDay = eArray[0];
let effectiveMonth = eArray[1];
let effectiveYear = eArray[2];
const effective_date = effectiveMonth '/' effectiveDay '/' effectiveYear;
let effectiveDateObj = new Date(effective_date);
// director release date object
let releaseDate = director.release_date;
const rArray = releaseDate.split("/");
let releaseDay = rArray[0];
let releaseMonth = rArray[1];
let releaseYear = rArray[2];
const release_date = releaseMonth '/' releaseDay '/' releaseYear;
let releaseDateObj = new Date(release_date);
let shouldReturn = true;
if (this.fromDateObj && this.fromDateObj > effectiveDateObj) {
shouldReturn = false;
}
if (this.toDateObj) {
if (this.fromDateObj) {
if (releaseDateObj < this.fromDateObj || releaseDateObj > this.toDateObj)
shouldReturn = false;
}
}
if (shouldReturn) {
return director;
}
});
}
}
}