Combine information from two arrays into a new array

I am attempting to create a new array with data that is not duplicated in two existing arrays. I have an object called this.subjects and properties named this.teacherData. I have extracted the subjects code from both of these and stored them in separate arrays. Now, my goal is to filter out any data that is not present in both arrays and store it in a third array.

subj: Subjects[];
teacherSubjects: string[];
data: string[];
filteredData: string[];
addsubject: AddTeacherSubject = new AddTeacherSubject();
teacherData: TeacherUpdateDataDto = new TeacherUpdateDataDto();

ngOnInit() {
this._curriculumService.getSubject(this.appSession.tenant.tenancyName)
.finally(() => { this.saving = false;})
.subscribe((result: listResultDtoOfSubjectDto) => {
  this.subjects = result.items;
  this.teacherSubjects = this.subjects.map(a => a.code);
  console.log("All Subjects =" + this.teacherSubjects);
 })

this._teacherService.GetTeacherUpdateData(this.appSession.tenant.tenancyName, 
this._sharedService.getMessage())
.finally(()=> { this.saving = false;})
.subscribe((result: TeacherUpdateDataDto) => {
  this.teacherData = result;
  this.subj = this.teacherData.subject;
  this.data = this.subj.map(a => a.code);
})
}

this.subjects DTO

(3) [subjectlistDto, subjectlistDto, subjectlistDto]
0 :
 subjectlistDto {name: "Mathematics", code: "mathematics", classCode: "bscs", 
 classNAME: "BSCS"}
1 :
 subjectlistDto {name: "English", code: "english", classCode: "bscs", 
 classNAME: "BSCS"}
2 :
 subjectlistDto {name: "Islamiat", code: "islamiat", classCode: "bscs", 
 classNAME: "BSCS"}

this.teacherData Dto

subject:Array(2)
0:
{code: "mathematics"}
1:
{code: "english"}

I want the filtered data to be stored in the filteredSubjects array. How can I achieve this?

Answer №1

If you are wondering about the best approach depending on the version of rxjs you are using, consider exploring forkJoin or combineLatest. These functions enable you to merge the outcomes of multiple observables into a single request. Take a look at an example of combine latest and fork join. Once you have both sets of data emitted, comparing items and filtering them into a third set becomes straightforward.

In case you intend to filter the arrays for unique items only, you can follow a process similar to this:

function getDistinctValues(array1, array2): [] {
    const finalArray = [...array1, ...array2];

    finalArray = finalArray.sort((item1, item2) => {
         return item1 === item2 ? 0 : item1 > item2 ? 1 : -1;
    });

    let pointer = finalArray.length-1;

    while(pointer > 0) {
        if(finalArray[pointer] === finalArray[pointer-1]) {
            finalArray.splice(pointer-1, 2);
            pointer--;
        }
        pointer--;
    }
    return finalArray;
}

Answer №2

Here is the technique I used

I simply invoked the Data function inside ngOnInit and

Data(items: string[], choices: string[]) {
this.resultantData = [];
for(var x = 0; x< items.length; x++) {
  if(choices.indexOf(items[x]) === -1){
    this.resultantData.push(items[x]);
  }
}
for(var y = 0; y<choices.length; y++) {
  if(items.indexOf(choices[y]) === -1){
    this.resultantData.push(choices[y]);
  }
}
return this.resultantData;
}

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

Is it possible to customize the visible columns in a mat table based on the size of the screen?

Using mat-table, I have specified the columns to display in an array: In TypeScript: displayedColumns: string[] = ['date', 'customer', 'project', 'performanceRecord', 'duration', 'status', &apos ...

Ways to initiate a fresh API request while utilizing httpClient and shareReplay

I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup: apicaller.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http& ...

The error message in TypeScript is indicating that the property 'x' is not found in the type '{}', which is required for a computed key

Description of a Typescript fragment: enum Field { age, bugs, } interface Foo { number_age: number; number_bugs: number; } function createFoo():Foo { let obj = {}; let index = 0; for (let key in Field) { obj['numb ...

What is the solution to the error message "Property 'permissions' is not found on type 'Navigator'"?

After being in draft form for a period of time, the permissions API now appears to be well supported. However, TypeScript still throws an error Property 'permissions' does not exist on type 'Navigator' when encountering code like: if (n ...

Error: 'ngForOf' is not recognized as a valid property of the 'tr' element

Since this afternoon, I've been facing a challenge that I can't seem to grasp. The issue lies within a service I created; in this file, there is an object from which I aim to showcase the data in a loop. An error message is displayed: NG0303: C ...

What is the proper method for utilizing TypeScript declarations (*.d.ts) and interfaces?

When working with interfaces in TypeScript, there are two main approaches to consider. The first involves defining them in regular .ts files and importing them as needed. The second option is to define the interfaces in .d.ts files and let the compiler dis ...

Accessing the authentication-required image source in Nativescript

I am attempting to show an image that is protected with OAuth in Nativescript. <Image src="url-to-secured-image"></Image> Therefore, I have to include the jwt token in the header of the request somehow. I searched and came across angular-img ...

Angular: The most efficient method for creating a customized HTML page with unique styles specifically for PDF generation

Struggling with PDF generation and the challenge of preparing hidden HTML is my current hurdle. The backend team has built a PDF generation service that requires passing an HTML string as a parameter. My task is to hide all HTML elements upon clicking the ...

Guide on displaying Angular 6 wildcard page for 404 errors using nginx

After successfully creating an application using Angular 6 and implementing the Angular 6 wildcard route for handling 404 errors, I encountered an issue when trying to serve the application with nginx. Despite building the app into index.html and static fi ...

Is it possible to refresh the webpage in Angular when the tab is clicked?

Can someone help me find a solution to reload an Angular app's page when the user selects the browser tab? I've been exploring using window.location.reload() for this purpose, but I need guidance on triggering it specifically when the tab is sel ...

What is the best way to display a block when a specific button is clicked?

I am looking to display this block only after clicking a button. Can someone help me achieve this in Angular? <div>Hello from some div block!</div> I have attempted the following: <button (click)="assign()">Button</button> <di ...

Typescript: Deciphering how to interpret a string with a mix of characters and numbers

Is there a way in TypeScript to add 40 to a variable of type string | number, and return a result as a string | number? My initial approach was to parse the variable to a number, then perform the addition, but how can I ensure that the variable is proper ...

TS1343: Usage of the 'import.meta' meta-property is restricted to when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext' mode

Whenever I attempt to compile my project into esm and cjs, I encounter this error consistently. This is the content of my package.json: { "name": "qa-data-tool", "version": "1.0.0", "descript ...

Utilize an embedded Angular project to access a property file within a Spring Boot application

Currently, I am working on a project where Angular 6 is embedded within a Spring Boot application. Everything is running smoothly so far and the index.html file for my Angular app is located in the resources folder of the Spring Boot application. I am no ...

Explore visuals in the component repository

I am currently working on an Angular 7 component library and am facing some challenges in adding images for buttons and other elements. My project structure is organized as follows: projects components src lib myComponent assets ...

Receiving an error with React Proptypes when using the union type Breakpoint

Struggling to assign the correct proptype to the material-ui Breakpoint type. The breakpoint values are: export type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl'; In my App.tsx file, I have the following ...

Displaying error messages in Angular Material upon clicking a button

I am struggling with validation using the <mat-form-field> and <mat-error>. The validation works as expected when the user tabs out of the input without filling it. However, I'm facing a challenge in making this error show up when a button ...

The error message "indexOf of undefined" appears when trying to read a property that does not exist within a new

Help Needed: The following error is happening: Cannot read property 'indexOf' of undefined at new HttpRequest (http.js:653) at HttpClient.request (http.js:1069) at HttpClient.get (http.js:1157) This occurs when I use the get() method from Ht ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Error: The nested property of the dynamic type cannot be indexed

Within my coding project, I've devised an interface that includes various dynamic keys for API routes, along with the corresponding method and response structure. interface ApiRoutes { "auth/login": { POST: { response: { ...