A guide on combining multiple arrays within the filter function of arrays in Typescript

Currently, I am incorporating Typescript into an Angular/Ionic project where I have a list of users with corresponding skill sets. My goal is to filter these users based on their online status and skill proficiency.

[
        {
            "id": 1,
            "name": "Vikram Shah",
            "online_status": "Online",
            "skills": [{
                    "id": 2,
                    "title": "CSS"
                },
                {
                    "id": 3,
                    "title": "JavaScript"
                },
                {
                    "id": 4,
                    "title": "Python"
                }
            ]
        },

        {
            "id": 1,
            "name": "Abhay Singh",
            "online_status": "Online",
            "skills": [{
                    "id": 1,
                    "title": "HTML"
                },
                {
                    "id": 2,
                    "title": "CSS"
                },
                {
                    "id": 3,
                    "title": "JavaScript"
                },
                {
                    "id": 4,
                    "title": "Python"
                }
            ]
        },

        {
            "id": 1,
            "name": "Test Oberoi",
            "online_status": "Online",
            "skills": [{
                    "id": 1,
                    "title": "HTML"
                },
                {
                    "id": 2,
                    "title": "CSS"
                },
                {
                    "id": 3,
                    "title": "JavaScript"
                },
                {
                    "id": 4,
                    "title": "Python"
                }
            ]
        }
    ]

The provided array showcases different skills each user possesses

 this.skill_types = [
      {"id":8,"title":"Cleaner", checked:false},
      {"id":7,"title":"Painter", checked:false},
      {"id":6,"title":"Plumber", checked:false},
      {"id":5,"title":"Carpenter", checked:false},
      {"id":4,"title":"Advisor", checked:false},
      {"id":3,"title":"Team Leader", checked:false},
    {"id":2,"title":"Management", checked:false},
    {"id":1,"title":"Administrator", checked:false}
   ];

This array holds the IDs of skills that need filtering

filterArr = [1, 3, 6];

My current approach works effectively with dual filtering criteria. However, I encountered issues when attempting to implement a secondary filter condition. The secondary filter should be active only when 'filterArr' is not empty.

return this.items = this.items.filter((thisUser) => {
        return thisUser.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1 &&
       thisUser.skills.some(c => this.filterArr.includes(c.id))
      });

The primary issue arises when no skill is selected for filtering; my intention is to display all users under such circumstances. Unfortunately, the logic in place does not function as intended. Ideally, no filters should apply if there are selected skills (filter conditions). I attempted an adjustment, but it led to further complications.

  let filteredByStatus = [];
  filteredByStatus = this.items.filter((thisUser) => {
    return thisUser.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1
  });

  //Condition can be applied if filtering is separated
  let filteredBySkills = [];
  filteredBySkills = this.items.filter((thisUser) => {
    return thisUser.skills.some(c => this.filterArr.includes(c.id))
  });

  //Expecting to join results from multiple filters
  return this.items = filteredByStatus.concat(filteredBySkills);

Unfortunately, the revised code snippet fails to deliver the expected outcome. I am seeking a solution to seamlessly merge arrays of similar objects without duplicating them.

Answer №1

Instead of combining arrays for filtering, consider using rxjs filter in your code.

return from(this.items)
    .pipe(
      filter(user => {
        return user.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1 
                && user.skills.some(c => filterArr.includes(c.id));
      })
    );

If you prefer to separate it out, you can modify the code like this:

return from(this.items)
    .pipe(
      filter(user => user.online_status.toLowerCase().indexOf(onlineStatus.toLowerCase()) > -1),
      filter(user => user.skills.some(c => filterArr.includes(c.id)))
    );

Check it out on Stackblitz: https://stackblitz.com/edit/angular-pk3w8b

Answer №2

If you adjust your condition slightly and include !this.filterArr.length within it (along with the user status as an OR condition), your entire condition will become true, allowing the user to receive the filter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to activate ngModelChange for a custom input field?

I have developed a custom input component and here is the code: html: <input class='ctrl__counter-input' maxlength='10' type='text' [value]="counterValue" [ngModel]="counterValue" (ngModelChange)="onKey(in ...

Extracting Values from a jQuery Array Object

Good day everyone! Here is the code I am currently working with: var items = []; $(xml).find("Placemark").each(function () { var tmp_latLng = $(this).find("coordinates").text(); tmp_latLng = tmp_latLng.split(","); items.push({ name: ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

Implementing the 'colSpan' attribute in ReactJS

I encountered an error saying "Type string is not assignable to type number" when attempting to include the colSpan="2" attribute in the ReactJS TypeScript code provided below. Any suggestions on how to resolve this issue? class ProductCategoryRow exten ...

Setting Authorization with username, password, and domain in Angular 2 HTTP Request

I am facing an issue with calling an API method hosted on another machine using Angular 2 component with Http. When accessing the API from a browser, I can connect by entering a username and password as shown below: https://i.stack.imgur.com/JJqpC.png Ho ...

Querying MongoDB for pulling/updating nested arrays in a paginated manner

In my database, I have a series of documents structured like this: Document1: { name: "tester1", reports: [{ name: "report1", type: "overflow" }, { name: "repor ...

`Problem encountered when trying to present JSON content in an Android Gridview`

Encountering difficulties while attempting to showcase JSON data in a Gridview within an Android application using the Volley library through a URL. The error message received is: com.android.volley.NoConnectionError:java.io.IOException The JSON data i ...

What methods can I use to adjust the size of a dynamic array of pointers without relying on a vector

If I needed to change the size of an array like this: int array[5]; I could use this approach: int* temp = new int [n]; ... array = temp; However, if my array is declared in this way: int *array[5]; Could the solution be something like this? int** temp ...

Generating and populating a grid with a 2D array based on input from the user

My latest project involves a program that prompts the user to input the dimensions and characters for a grid. However, upon printing the grid, it appears flat rather than in two dimensions. public static void main(String[] args) { System.out.printl ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

Is there a way for me to retrieve the text generated by OpenAI in the completion response?

let gptResponse = await openai .createCompletion({ model: "davinci", prompt, max_tokens: 60, temperature: 0.9, presence_penalty: 0, frequency_penalty: 0.5, best_of: 1, n: 1, stre ...

Unable to locate template while working with Angular 2 in ASP MVC framework

I am currently utilizing angular 2 within ASP.NET MVC. This particular component is referred to as the "other" component: import { Component } from '@angular/core'; @Component({ selector: 'other-app', templateUrl: './app ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Descending order of index numbers

I have a table with indexing numbers and when I add a new row, I want the current value to be displayed in the top index number 2. However, my current code is displaying it as 0,1,2 instead of 2,1,0. Here is my HTML file: <mat-table #table [dataSource ...

The 'DOCUMENT' module (imported as 'i23') could not be located within '@angular/platform-browser'

During my upgrade from Angular version 7 to 8, I encountered an error when building the project even though I am not using DOCUMENT. It seems like something is causing this issue that I am overlooking. I have thoroughly checked all the files and confirmed ...

I suggest installing the ng2-search-filter package for easy search functionality

Is there a recommended alternative to ng2-search-filter? I encountered an error with this one: 'Ng2SearchPipeModule' does not appear to be an NgModule class.(-996002). The error message in ng2-filter.module.d.ts(1, 22) suggests that the library ( ...

Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this: <table id="rooms"> <tr> <td>Room Type</td><td>Beds</td><td>Q.ty</td ...

Utilize Angular2 services to showcase a JSON object on the front end

Seeking assistance with displaying a JSON file containing multiple arrays on the front-end using Angular2 Services in Typescript. Can anyone provide guidance? If someone could assist in improving this code by incorporating Model and Interface classes, it ...