How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript

Original Array:

[
{"Id":"3","DisplayName":"Fax"},
{"Id":"1","DisplayName":"Home"},
{"Id":"4","DisplayName":"Mobile"},
{"Id":"2","DisplayName":"Office"},
{"Id":"5","DisplayName":"Other"}
]

Selected Array:

[
{"PhoneNumberId":127436,"ContactId":22222,"IsPrimary":true, "PhoneType":  {"Id":"2","DisplayName":"Office"},"PhoneNumber":"111111111","Extension":"","DisplayPhoneNumber":"111-111-1111"},
{"PhoneNumberId":127437,"ContactId":22222,"IsPrimary":false,"PhoneType":{"Id":"3","DisplayName":"Fax"},"PhoneNumber":"111111111","Extension":null,"DisplayPhoneNumber":"111-111-1111"},
{"PhoneNumberId":173825,"ContactId":22222,"IsPrimary":false,"PhoneType":{"Id":"4","DisplayName":"Mobile"},"PhoneNumber":"111111111","Extension":"","DisplayPhoneNumber":"111-111-1111"}
]

To get the desired result, I attempted this filter method but it did not work as expected.

this.filteredArray = this.originalArray.filter(item => !this.selectedArray.some(itemToRemove => itemToRemove['Id'] == item['Id']));

The end goal is to have the original array filtered to display only specific items:

Filtered Array:

[
{"Id":"1","DisplayName":"Home"},    
{"Id":"5","DisplayName":"Other"}
]

Answer №1

Consider creating a list of unnecessary IDs and then using it to filter the primary list

var PhoneTypesAll = 
[
{"Id":"3","DisplayName":"Fax"},
{"Id":"1","DisplayName":"Home"},
{"Id":"4","DisplayName":"Mobile"},
{"Id":"2","DisplayName":"Office"},
{"Id":"5","DisplayName":"Other"}
];

var PhoneTypesSelected = 
    [
    {"PhoneNumberId":127436,"ContactId":22222,"IsPrimary":true, "PhoneType":  {"Id":"2","DisplayName":"Office"},"PhoneNumber":"111111111","Extension":"","DisplayPhoneNumber":"111-111-1111"},
    {"PhoneNumberId":127437,"ContactId":22222,"IsPrimary":false,"PhoneType":{"Id":"3","DisplayName":"Fax"},"PhoneNumber":"111111111","Extension":null,"DisplayPhoneNumber":"111-111-1111"},
    {"PhoneNumberId":173825,"ContactId":22222,"IsPrimary":false,"PhoneType":{"Id":"4","DisplayName":"Mobile"},"PhoneNumber":"111111111","Extension":"","DisplayPhoneNumber":"111-111-1111"}
    ]

var IdsToExclude = PhoneTypesSelected.map(a=> a.PhoneType?.Id)
var result = PhoneTypesAll.filter(item => !IdsToExclude.includes(item.Id))

console.log(result)

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

How can I eliminate the immediate forward slash (/) following a hash (#) in an Angular application

After configuring my angular 8 app routing with {useHash:true}, I encountered an issue. Whenever I open a URL in the browser, such as https://localhost:4200/#/todo https://localhost:4200/#/todo/12 I do not want that additional "/" immediately after "#". ...

Implementing conditional wildcard route redirection in an Angular routing module

Is there a way to manage redirect routes when users enter the wrong URL using wildcards controlled by conditions? In my project, I have 3 main modules that are separate, and each of them has specific conditions for user access based on roles. The issue I ...

Troubleshooting: ngModel in Angular 2 Component does not properly update the parent model

I have been attempting to develop a wrapper component for input elements like checkboxes, but I am facing an issue where the parent variable (inputValue) is not updating even though it has been defined as an ngModel. The code snippet for my component look ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

How can I handle the different data type returned by ReactDom.render?

My main focus is on rendering Markdown. Additionally, I also need to parse HTML which is passed as a string. In this scenario, children represents the HTML passed as a string, while isParseRequired indicates if parsing is needed. import cx from 'clas ...

Is it possible for me to modify the appearance of the ion-searchbar in Angular?

Currently working on an angular ionic project and I'm looking to personalize the design of the ion-searchbar. In the default template, the search bar icon is positioned on the left side. My goal is to adjust the placement of the icon and have it situa ...

Interactive mat-select within Angular material table

I have retrieved data from an endpoint and displaying it in a material table. However, I also have an additional column requestedStatus, which contains a mat-select with 2 options. I want the selected option to dynamically update the row by adding a new ke ...

Having trouble reading a file in Android 11 due to a Capacitor Filesystem error

I attempted to access a file within my emulator using the readFile function of Capacitor filesystem. The file I am trying to manipulate is located in the Download folder of the emulator, and upon execution, the function returned the following error: Erro ...

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

Sometimes encounter undefined values after assigning them through the service

One of the challenges I am facing is handling public fields in my service: @Injectable() export class ShareDataService { // Some code public templateForCurrencyCOS; public templateForPercentCOS; public templateForCurrencyCOGS; public te ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

Sometimes the PDF does not display even though the iframe src attribute is updating in Angular 6

I have encountered an issue with displaying a PDF file in my code. Sometimes the PDF shows up correctly, but other times it fails to load. I even tried using an iFrame instead of embed but faced the same scenario. Can anyone provide assistance? Here is my ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Navigating through various product categories in Angular's routing system

Greetings! I am currently building a Shop Page in Angular 4 and encountering an obstacle with Angular routing. The issue arises when a user clicks on a product category, the intention is for the website to direct them to the shop page. On the homepage, th ...

Troubleshooting radio name input binding in Angular 2

In Angular2, there seems to be an issue with one-way binding to the name attribute for a group of radio inputs. For example: <div [ngFormModel]="form"> <input type="radio" [name]="varName" [id]="id1" ngControl="r1"> <input type="radio" ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

The nz-switch function is malfunctioning as a result of an update that has affected its value

<form [formGroup]="businessFoodHygieneForm"> <div class="box p-4 d-flex jc-between ai-center"> <span> Food Hygiene Link </span> <label> <nz-switch class="switch- ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...