Search code examples
typescripttypeorm

Filter array with multiple conditions in Typescript


I want to create a filter with multiple conditions in Typescript. Let's suposse I have this array:

{
    "id": 1513,
    "procedure": {
        "title": "Sample Procedure 1"
    },
    "category": {
        "title": "Press"
    },
    "status": {
        "status": "IN PROCESS"
    },
    "deadline": {
        "deadline": "OUT OF DEADLINE"
    }
},
{
    "id": 1514,
    "procedure": {
        "title": "Sample Procedure 2"
    },
    "category": {
        "title": "Press"
    },
    "status": {
        "status": "SUBMITTED"
    },
    "deadline": {
        "deadline": "WITHIN DEADLINE"
    }
},

I want the user can filter this array using multiple options, for example: Filter the procedures with deadline in "WITHIN DEADLINE" and status in "IN PROCESS".

Edit: I require the user-selected conditions to come from the body, and based on these conditions, generate the new filtered array


Solution

  • const arr = [{
        "id": 1513,
        "procedure": {
            "title": "Sample Procedure 1"
        },
        "category": {
            "title": "Press"
        },
        "status": {
            "status": "IN PROCESS"
        },
        "deadline": {
            "deadline": "OUT OF DEADLINE"
        }
    },
    {
        "id": 1514,
        "procedure": {
            "title": "Sample Procedure 2"
        },
        "category": {
            "title": "Press"
        },
        "status": {
            "status": "SUBMITTED"
        },
        "deadline": {
            "deadline": "WITHIN DEADLINE"
        }
    },
    {
        "id": 1515,
        "procedure": {
            "title": "Sample Procedure 3"
        },
        "category": {
            "title": "Press"
        },
        "status": {
            "status": "IN PROCESS"
        },
        "deadline": {
            "deadline": "WITHIN DEADLINE"
        }
    },]
    
    const result = arr.filter(item => item.status.status === 'IN PROCESS' 
        && item.deadline.deadline === 'WITHIN DEADLINE')
    console.log(result)
    
    

    Output:

    [
      {
        id: 1515,
        procedure: { title: 'Sample Procedure 3' },
        category: { title: 'Press' },
        status: { status: 'IN PROCESS' },
        deadline: { deadline: 'WITHIN DEADLINE' }
      }
    ]
    

    Edit:

    For typeorm you can add OR into an existing WHERE expression:

    createQueryBuilder("entity")
        .where("entity.status = :status", { status: "IN PROCESS" })
        .orWhere("entity.deadline = :deadline", { deadline: "WITHIN DEADLINE" })
    

    https://typeorm.io/select-query-builder#adding-where-expression