How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items.

For example:

employees: any;
  offices: any;
  constructor() {
    this.employees = [
      { fname: "John", lname: "James", state: "New York" },
      { fname: "John", lname: "Booth", state: "Nebraska" },
      { fname: "Steve", lname: "Smith", state: "Nebraska" },
      { fname: "Stephanie", lname: "Smith", state: "New Hampshire" },
      { fname: "Bill", lname: "Kydd", state: "New Mexico" },
      { fname: "Bill", lname: "Cody", state: "Wyoming" }
    ]

    this.offices = [
      { state: "New York", city: "Albany" },
      { state: "Nebraska", city: "Omaha" },
      { state: "New Mexico", city: "Albuquerque" },
      { state: "New Hamshire", city: "Manchester" },
      { state: "California", city: "Redding" }
    ]
let finalOffice = this.employees.filter((state: any) => !this.offices.include(state));
console.log(finalOffice);

}

The desired result for the third array would be something similar to:

empofclist = [
  {state: "New York", city: "Albany", fname: "John",lname: "James"},
  {state: "Nebraska", city: "Omaha",fname: "John",lname: "Booth"},
  {state: "Nebraska", city: "Omaha",fname: "Steve",lname: "Smith"},
  {state: "New Mexico", city: "Albuquerque",fname: "Bill",lname: "Kydd"},
  {state: "New Hamshire",city: "Manchester",fname: "Stephanie",lname: "Smith"}
]

It's worth noting that there are multiple entries for Nebraska, one for each person, and no entry for California as there are no employees there, and no listing for Bill Cody because there is no office in Wyoming.

If you have any recommendations on where I can gather more information on this topic, please let me know!

Answer №1

            this.members = [
                  { first: "Sarah", last: "Johnson", location: "Texas" },
                  { first: "Mary", last: "Smith", location: "California" },
                  { first: "Mike", last: "Jones", location: "Ohio" },
                  { first: "Emily", last: "Davis", location: "Texas" },
                  { first: "Chris", last: "Robinson", location: "Florida" },
                  { first: "Daniel", last: "Brown", location: "Arizona" }
            ];


            this.places = [
                  { location: "California", city: "Los Angeles" },
                  { location: "Ohio", city: "Columbus" },
                  { location: "Arizona", city: "Phoenix" },
                  { location: "Texas", city: "Austin" },
                  { location: "Florida", city: "Miami" }
            ]

            let resultArr = [];
            let self = this;
            for (let x=0; x<self.members.length; x++) {
                    for (let y=0; y<self.places.length; y++) {
                            if (self.members[x]['location'] === self.places[y]['location']) {
                                    resultArr.push(self.members[x]);
                                    resultArr[resultArr.length - 1]['city'] = self.places[y]['city'];
                                    break;
                            }
                    }
            }

console.log(resultArr);

You may want to consider a similar approach.

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 insert commas between the numbers within an array?

import numpy import re data = [] with open("C:/Users/PycharmProjects/firsttry.txt", 'r') as textfiles: for line in textfiles: data_row = [item.strip() for item in line.split(',')] data.append(data_row) print(data) Th ...

Discovering the Java Map's value in Typescript

My application's backend is built using Spring Boot and the frontend is Angular 7. I need to send a map as a response, like this: Map<String, Object> additionalResponse = new HashMap<>() { { put("key1"," ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Encountering a range error above zero when working with a JSON array in Dart

When attempting to access position 1 of the array in my Flutter Dart code, I encounter a range error 0:1. Despite trying different methods to json.decode(data), I consistently receive the following error message: [ERROR:flutter/lib/ui/ui_dart_state.cc(14 ...

What is the best method for dynamically compiling components in Angular 11?

Within our application, we have implemented a directive that allows for the dynamic display of Angular components: import {Compiler, Component, Directive, Input, ModuleWithComponentFactories, NgModule, OnDestroy, ViewContainerRef} from '@angular/core& ...

Error! Unexpected closure occurred while creating an Angular CLI project with npm

After cloning an Angular (4+) CLI project onto a new machine and running npm install, I encountered an error that reads as follows. This project works perfectly fine on other computers: npm ERR! premature close npm ERR! A complete log of this run can be ...

Contrasting `Function` with `(...args: any[]) => any`

Can you explain the difference between Function and (...args: any[]) => any? I recently discovered that Function cannot be assigned to (...args: any[]) => any. Why is that so puzzling? declare let foo: Function; declare let bar: (...args: an ...

The BeanStub initialization failed due to a missing bean reference to frameworkOverrides

I recently updated my ag-grid version to 23.2.0 in my Angular 7 project. Everything was working fine, but when I tried filtering a page and then navigating away, I encountered the following error message: "unable to find bean reference frameworkOverrides ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

Creating Dynamic Templates in Angular 6

We are currently rendering the template dynamically in our application by utilizing AngularJS's $compile to compile HTML on the fly. I am wondering if there is a similar feature in Angular 6 that allows us to manually compile HTML. I have searched for ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

Interactive Bootstrap 4 button embedded within a sleek card component, complete with a dynamic click event

I am trying to create a basic card using bootstrap 4 with the following HTML code. My goal is to change the style of the card when it is clicked, but not when the buttons inside the card are clicked. Currently, clicking on the test1 button triggers both ...

Tips for identifying errors in Angular's HTTPClient.post() method when working with generics

This question has been asked numerous times on SO, but none of the responses address my issue. Therefore, I am rephrasing it. Here is a method (within a service) that performs a post request. makePostReq<T>(reqObj: {url:string, body:any, headerDa ...

Eliminating Elements from Array

Hey there, I'm working with an array in R: A<-array(c(1:12), dim=c(6,2)) I'm trying to filter out the first 3 rows where the value in the first column is less than 3, and for the last 3 rows I want to keep those where the value in the first c ...

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Tips for utilizing [ngClass] with various class situations in Angular4

My current div structure is as follows: <div class="class-a" [ngClass]="{'class-b': !person.something}"> However, I now need to add an additional condition... I want the div to have class-a if one condition is met, class-b if another con ...

Paths: Integrate a variety of components along with essential information

With 3 components in hand, everything works smoothly when I run them on AppComponent: <app-sections #appSection></app-sections> <app-form #mainForm [section]="appSection.currentSection"></app-form> <app-match [bestMatchHTMLEleme ...

Refresh the Angular component following updates to the store

Working with NGRX/Redux for the first time, I am puzzled by why my component fails to update after adding a new item to an array in the store. Within my main component, these properties are defined: productLines$: Observable<ProductionLine[]>; produ ...