Home > database >  How to filter an array based on multiple conditions?
How to filter an array based on multiple conditions?

Time:10-13

How to filter an array based on multiple conditions? I have multiple checkboxes checked by default and I want to filter based on start_date and end_date:

  • future:
    start_date is later than today

    past: end_date is later than today date

    in_progress: start_date is later or equal to today but end_date is not later than today date

<input v-model="future" type="checkbox" />
<input v-model="past" type="checkbox" />
<input v-model="in_progress" type="checkbox"/>
data: function () {
  return {
    past: true,
    future: true
    in_progress: true
    items: [
   {
      "name":"Test",
      "start_date":""2022-01-01T07:00:00-08:00"",
      "end_date":""2022-03-01T07:00:00-08:00"",
      "id":"2asfa3r9adsgu83yf83"
   },
   {
      "name":"Test",
      "start_date":""2020-01-01T07:00:00-08:00"",
      "end_date":""2020-02-01T07:00:00-08:00"",
      "id":"1asfa3r9adsgu83yf83"
   },
   {
      "name":"Test",
      "start_date":""2021-10-12T07:00:00-08:00"",
      "end_date":""2022-10-19T07:00:00-08:00"",
      "id":"6asfa3r9adsgu83yf83"
   },
]
  }
}

CodePudding user response:

for in_progress

const items = [
   {
      "name":"Test",
      "start_date":"2022-01-01T07:00:00-08:00",
      "end_date":"2022-03-01T07:00:00-08:00",
      "id":"2asfa3r9adsgu83yf83"
   },
   {
      "name":"Test",
      "start_date":"2020-01-01T07:00:00-08:00",
      "end_date":"2020-02-01T07:00:00-08:00",
      "id":"1asfa3r9adsgu83yf83"
   },
   {
      "name":"Test",
      "start_date":"2021-10-12T07:00:00-08:00",
      "end_date":"2022-10-19T07:00:00-08:00",
      "id":"6asfa3r9adsgu83yf83"
   },
]

const in_progress = items.filter(item => Date.now() > new Date(item.start_date) && Date.now() < new Date(item.end_date))
console.log(in_progress)

CodePudding user response:

You can use .filter() on the array and perform filtering.

const data = () => {
  return {
    past: true,
    future: true,
    in_progress: true,
    items: [
   {
      name:"Test1",
      start_date:"2022-01-01T07:00:00-08:00",
      end_date:"2022-03-01T07:00:00-08:00",
      id:"2asfa3r9adsgu83yf83"
   },
   {
      name:"Test2",
      start_date:"2020-01-01T07:00:00-08:00",
      end_date:"2020-02-01T07:00:00-08:00",
      id:"1asfa3r9adsgu83yf83"
   },
   {
      name:"Test3",
      start_date:"2021-10-12T07:00:00-08:00",
      end_date:"2022-10-19T07:00:00-08:00",
      id:"6asfa3r9adsgu83yf83"
   },
]
  }
}

let tempItems = data().items
const newtempItems = tempItems.filter(item => Date.parse(item.start_date) >= Date.now())
console.log(newtempItems);

  • Related