Find the difference between two observable values and output the outcome in an array using Angular Rxjs

I have been struggling to compare two observable methods and retrieve the desired output. Although I attempted an example, the expected outcome was not achieved. Hopefully, the following example (what I tried) will clarify my question.

GetCountries() : Observable<any>
{
  return this.http.GetCountries().subscribe(data => {
    return  data;
  })
}

GetSelectedCities() : Observable<any>
  {
    return this.http.GetCities().map(data => {
      return   data
    });

  }

let cities = [{name:'new york', id:1},
    {name:'paris', id:2},
    {name:'london', id:3}]

    let countries = [{name:'usa', id:1, city:'new york'},
    {name:'germany', id:2,city:'berlin'},
    {name:'france', id:3,city:'marseille'},
    {name:'netherland', id:3,city:'amersterdam'}]

GetNotSelectedCities()
{
  this.GetCountries.do(data => {
    this.GetSelectedCities.do(response => {
      data.filter(x=> return response.filter(d=> d.city !== x.name ) )
    })
  })
}

However, despite my efforts, I am receiving a list of cities instead of the intended result:

[{name:'germany', id:2,city:'berlin'},
    {name:'france', id:3,city:'paris'},
    {name:'netherland', id:3,city:'amsterdam'}]

Answer №1

Here's a suggestion to try out:

RetrieveUnselectedLocations() {
   forkJoin([
      this.RetrieveCountries(),
      this.RetrieveSelectedCities(),
   ])
   .pipe(
       map(([countries, cities]) => {
          return countries.filter(country => !cities.find(c => c.name === country.city));
       })
   )
   .subscribe(notSelected => {
      console.log(notSelected);
   });
}

Answer №2

On the other hand:

ObtainCountries() : Observable<any>
{
  return this.http.GetCountries();
}

AcquireSelectedCities() : Observable<any>
  {
    return this.http.GetCities();

  }

let cities = [{name:'new york', id:1},
    {name:'paris', id:2},
    {name:'london', id:3}]

    let countries = [{name:'usa', id:1, city:'new york'},
    {name:'germany', id:2,city:'berlin'},
    {name:'france', id:3,city:'marseille'},
    {name:'netherland', id:3,city:'amersterdam'}]

RetrieveNotSelectedCities()
{
   return combineLatest([this.ObtainCountries(), this.AcquireSelectedCities()]).pipe(map([countries, cities]) => {
    return countries.filter(country => cities.filter(d=> d.city !== country.name ).length > 0 );
}))
}

Nonetheless, you will need to subscribe to this when and where you intend to utilize this combinelatest.

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

The installation of @angular/router seems to have encountered an error

I am attempting to update my @angular/router dependency from version 2.0.0 to 3.0.0-alpha.7. I have included it in my package.json file. { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently &bs ...

The functionality of router.navigate in Angular 5 seems to be malfunctioning

I am struggling with redirecting a user to another page based on a certain condition. Here is an example of my login component: ngOnInit() { console.log(">>> router", this.router) console.log(">>> activatedRoute", this.activate ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Angular 7 API request fails to access PHP session data

I am working on creating a simple login system with Angular and utilizing sessions. I have two PHP files along with the Angular files that are involved in this process. Let's start with PHP file 1: session_start(); header('Access-Control-Allow- ...

Restrictions on classes in Typescript using generics

I'm currently working on a straightforward Local Storage utility method. My goal is to retrieve an entry based on a key and a specified type. Here's the implementation: get<T>(key: string): T { const data = localStorage.getItem(key); ...

"Revolutionizing User Experience with Angular's Inline Editing Feature

I'm currently working on developing an "Inline-Edit" feature in Angular. Below is the concept and various use cases: <toggle-editor> <toggle-normal></toggle-normal> <toggle-edit></toggle-edit> </toggle-editor> ...

Issue encountered while importing supercluster in TypeScript (TypeError: Unable to assign property 'options' to an undefined variable)

After attempting to import supercluster in TypeScript, I encountered the following error. Any helpful insights would be appreciated. ExceptionsManager.js:86 TypeError: Cannot set property 'options' of undefined This error is located at: ...

Angular 5: Autosuggestion feature functions perfectly in Chrome, experiencing difficulties in Internet Explorer

I have integrated an autosuggestion feature using Angular 5, pulling suggestion values from an API. Here is the HTML Code : <div class="col col-lg-4"> <label for="insuranceCompanyName"> Insurance Company Name </label> ...

Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue. There are two drop-down menus: First Drop-down The options in the first menu are populated from an array of objects Example Code, ts: {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819", ...

Is there a way to designate an image to a variable or object property through manual assignment?

Is it feasible to manually link an image file from the assets folder to an object property? Let's say I have an image stored at 'assets/images/ProfilePlaceholder.png'. Would it be possible to assign the image file as a value to an object pr ...

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

TypeScript and Node.js: The type of 'this' is implicitly set to 'any'

Help Needed with TypeScript issue: An issue is arising in my TypeScript code related to a mongoose schema's post function. It is used to generate a profile for a user upon signing up, using the User model. Even though the code functions properly, th ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

Difficulty arises when attempting to add multiple properties simultaneously in TS/JS through the use of map, set, and get functions

Struggling to create a summary of an array of objects grouped by one property value and summing 2 or more properties. Unfortunately, my current approach only provides 2 values: the grouped-by property and the first summed property. I can't seem to f ...

Opt for Readme display over index.html

I'm just starting out and I have a question about Github: Is there a way to build a page using the index.html file within a folder instead of the readme file? I've successfully built many pages where the index file is not located in a folder. Ho ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

Struggling to generate a user using the supabase.auth.admin.createUser() function, encountering the error "Failed to create new user due to database error"

While working on my Next.js project, I encountered an issue when trying to create a user using the supabase.auth.admin.createUser() method. The error message I received was: { message: "Database error creating new user" name: "AuthApiE ...

Ways to effectively implement the setState function through the use of the useDerived

While attempting to pass the translateX.value to the parent using setXPos, I encountered an error stating "Tried to synchronously call function {bound dispatchSetState} from a different thread." Even though I tried using runOnJS(setXPos)(event.translatio ...

Is it possible to view Intersection types in Typescript as a subtype of the types included in the intersection?

I've been exploring the concepts of generic types and subtypes in TypeScript, but despite my efforts to delve into the official documentation, I'm still left with a lingering question. Specifically, I'm curious: Is an intersection type poten ...