Combining the MergeMap and Map operators in RxJS using Typescript

Struggling to grasp the concept of RxJS, I am currently learning and trying to understand this code snippet:

mapOfPeople = new Map<number, any>();

const people = [
  { name: 'Sue', age: 25 },
  { name: 'Joe', age: 30 },
  { name: 'Frank', age: 25 },
  { name: 'Sarah', age: 35 }
];

from(people)
  .pipe(
    groupBy(
      person => person.age,
      p => p
    ),
    mergeMap(group => zip(of(group.key), group.pipe(toArray())))
  )
  .subscribe(console.log);

Referencing a tutorial for guidance, I aim to store the output in the specified hashmap. I am puzzled about how to do this effectively. Any suggestions or insights?

Answer №1

Here's a suggestion for enhancing this code snippet by simply appending a reduce operator:

from(people)
  .pipe(
    groupBy(
      person => person.age,
      p => p
    ),
    mergeMap(group => zip(of(group.key), group.pipe(toArray()))),
    reduce((acc, v) => {
      acc.set(v[0], v[1])
      return acc
    }, new Map<number, any>())
  )
  .subscribe(result => modifiedResults = result);

Answer №2

I'm having trouble compiling your original code, and I'm not entirely certain of the purpose of the zip component in this particular scenario.

One potential solution is to utilize the subscribe function handler. Currently, it's set to console.log, but you can customize it to any format like (arg) => void (a function that receives an item from the observable and processes it in some manner).

Check out this example below, where we collect an array of individuals based on their age:

type Person = { name: string, age: number};

const mapOfPeople = new Map<number, Person[]>();

const people = [
  { name: 'Sue', age: 25 },
  { name: 'Joe', age: 30 },
  { name: 'Frank', age: 25 },
  { name: 'Sarah', age: 35 }
];

from(people).pipe(
  groupBy(person => person.age),
  mergeMap(group => group.pipe(toArray()))
).subscribe(people => {
  // key representing the age of individuals in this group
  const { age } = people[0];

  // assign these individuals to the corresponding age in the map
  mapOfPeople.set(age, people);
});

Answer №3

peopleData: any;

const peopleList = [
  { name: 'Sue', age: 25 },
  { name: 'Joe', age: 30 },
  { name: 'Frank', age: 25 },
  { name: 'Sarah', age: 35 }
];

from(peopleList)
  .pipe(
    groupBy(
      person => person.age,
      p => p
    ),
    mergeMap(group => zip(of(group.key), group.pipe(toArray())))
  )
  .subscribe(result => peopleData = result /*or process the data as needed*/);

To learn more, visit: observable

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

I am not encountering any error messages, but when I attempt to click on the form, the mouse cursor does not change to the expected form type

While there are no errors showing up in the Chrome Developers Error code, I am facing an issue with my form where the text fields are not visible. It should be a simple task, but it has turned into a headache for me. I would greatly appreciate any help i ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

Mastering the BFCache management in React for optimal performance

Before redirecting to an external payment provider, I display a loading screen to account for longer load times. If the user decides not to complete the payment and navigates back using gestures or the browser's back button, the page is pulled from t ...

Maximize the sum of diverse numbers effectively

I have an array that contains objects structured like this: [ { "id": 91, "factor": 2, "title": "Test Product", "price": 50, "interval": 1, "setup": 0, "optional": false }, { "id": 92, "factor": 1, "title": "A ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

Stop the instantiation of type alias

Is there a way to restrict the creation of an instance of a type alias, such as ValidatedEmail? type ValidatedEmail = { address: string; validatedOn: Date } Let's say we have functions validateEmail and sendEmail. const validateEmail = (email): Valid ...

Executing one controller function from another controller in Typescript

There are two typescript controllers in my project Controller A { public methodOfA() {//perform some action} } Controller B { public methodOfB() {//perform some action} } I am trying to implement the following functionality Controller B { ...

Using *ngIf and *ngFor in Angular to switch between divs depending on their index values

Is there a way to toggle between two divs based on the index value using *ngIf in Angular? I have attempted to do so by toggling boolean values of true and false, but my current approach is not working. Here is what I have tried so far: <div *ngFor=&qu ...

What is the best way to view an image stored in a database in a separate window?

I am currently working on a page that displays multiple images, with each image's path stored in the database. Using PHP, I retrieve and display these images based on their paths. My goal is to enable users to click on an image and have it open in a ...

Selection dropdown not being populated by ng-options

After trying numerous examples to implement the changes, I am still facing issues. Even though I have an ng-model and clearly defined the object property I want to receive, it is not functioning as expected. Any assistance would be appreciated. Here is th ...

What is the best method to ensure a jQuery function only runs once, even when declared multiple times within a form?

Whenever a button with a specific class is clicked in a document, a jQuery function is triggered to perform a certain action. See example below. $(document).on('click', '.tambah', function(){ alert('tombol tambah telah ditekan ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access databa ...

Struggling to track down the issue in my ts-node express project (Breakpoint being ignored due to generated code not being located)

For my current project, I decided to use the express-typescript-starter. However, when I attempted to debug using breakpoints in VS Code, I encountered an issue where it displayed a message saying "Breakpoint ignored because generated code not found (sourc ...

"Encountering a NodeJS Error when trying to Connect to MongoDB

Currently, I am experimenting with a basic Hello World App using MongoDB, Express, Swig, and NodeJS Utilizing the latest version of Node.js along with other dependencies. Operating on Chrome 46.0 (64 bit) with Mac OS X 10.9.5 This is the code from my ap ...

Successfully executing a JQuery ajax GET request results in receiving truncated data

Recently, I encountered an issue while retrieving a large amount of data from my server using a JQuery ajax GET request. The data returned was truncated unexpectedly (as shown in the image below). However, when I tried accessing the same URL directly throu ...

I encountered an error while working with the angular factories in my project

Encountering an error despite injecting the factory into the controller. Any help or suggestions to resolve this issue would be much appreciated. Error: [$injector:unpr] http://errors.angularjs.org/1.3.16/$injector/unpr?p0=<div ng-view="" class="ng-s ...

Is it not the case that using spread syntax does not make a reference to the original array?

I am currently facing an issue with my React application. I have two Object arrays in my state, one called names and the other called shuffledNames. I am attempting to create a copy of the names array and shuffle it into the shuffledNames array. However, w ...

Loading excessive amounts of HTML onto a single webpage

Currently, I am involved in the creation of a HTML client for a collaborative game project. This client will require multiple scenes/pages such as the login, lobby, game page, and more. While I usually have no issue with page navigation, the client must ...

Having difficulties with binding 'this' in Angular/Javascript?

Currently, I am attempting to integrate the pullToRefresh package into my Angular application. Here is the code snippet: const ptr = pullToRefresh.init({ mainElement: '.dashboard-container', onRefresh() { ...

Updating Angular 2 template based on specific conditions of model values

I want to update a view only when the total votes reach a number that is a multiple of ten. I am incrementing a random element in an array called rows every 10 milliseconds, ultimately adding up to the total number of votes. Is there a simple way in angula ...