mardi 15 juin 2021

filter array of objects and return Boolean

I have an array of objects I am need to filter it based on user's name, startDate, endDate and Part.

This is a short version of the array I receive via a web service.

const arr = [{
    startDate: "12-6-2021",
    endDate: "12-6-2021",
    user: {
      name: "John"
    },
    Part: "PM"
  },
  {
    startDate: "12-6-2021",
    endDate: "12-6-2021",
    user: {
      name: "John"
    },
    Part: "AM"
  },
  {
    startDate: "12-6-2021",
    endDate: "12-6-2021",
    user: {
      name: "John"
    },
    Part: "DAM"
  },
  {
    startDate: "11-6-2021",
    endDate: "11-6-2021",
    user: {
      name: "Alise"
    },
    Part: "AM"
  },
  {
    startDate: "13-6-2021",
    endDate: "13-6-2021",
    user: {
      name: "Emily"
    },
    Part: "AM"
  }
];

the query/filtering should look into the array for single or double entries for the same user based on the same startDate and endDate. This is important as the entry could contain both AM and PM values. If it contains both AM and PM, then I need to display a full day, otherwise show whatever part of the day has been entered.

Example:

let val = "";
if(user.name=="John" && startDate=="12-6-2021" && endDate=="12-6-2021" && Part=="AM" && Part=="PM"){
  val="FullDay";
}else if(Part of the day AM or PM){
  //show that Part of the day only
 val="AM/PM";
}

I have come with something like this:

let val="";
if(arr.filter(a => a.startDate == "12-6-2021" && (a.Part == "AM" || a.Part == "PM").length>1){
val="FullDay";
}else if(arr.find(a => a.startDate == "12-6-2021" && a.Part == "AM")){
val="AM";
}else{
val="PM";
}

Is this the right way? How can I improve on what I have at the moment? How can I return Boolean from a filtered array of objects? How can I make sure that the specific condition is executed first and then the general one? Thank you.

Aucun commentaire:

Enregistrer un commentaire