Combining results from two streams in RXJS to create a sorted array

I currently have two different streams which I will name as follows:

const firstStream = Rx.of([
  {
    first: 'first',
  }, {
    third: 'third',
  }
]);

const secondStream = Rx.of([
  {
    second: 'second'
  }, {
    fourth: 'fourth'
  }
]);

My goal is to create a combined stream that merges the results of these two streams and sorts the output array in a specific order like this:

const resultArr = [
  {
    first: 'first',
  }, 
  {
    second: 'second'
  },
  {
    third: 'third',
  },
  {
    fourth: 'fourth'
  }
];

I attempted to use combineLatest along with the RxJS flatMap operator, but encountered issues. To play around and troubleshoot, I have provided a StackBlitz playground link here: StackBlitz

I believe there are multiple solutions to achieve this task. If anyone has suggestions or can assist me, it would be greatly appreciated :)

Answer №1

const { source, combine } = rxjs;
const { aggregate, transform, chainMap } = rxjs.operations

const x = source(['one', 'three']);
const y = source(['two', 'four']);

const sortedMapping = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
}

combine(x, y).pipe(
  // waiting until all sources are completed,
  // combining values into an array
  aggregate((result, item) => result.concat(item), []),

  // arranging the array based on specified sorting criteria
  transform(array => array.sort((a, b) => sortedMapping[a] - sortedMapping[b])),

  // flattening the array into a sequence
  chainMap(array => array),
).subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js" integrity="sha256-mNXCdYv896VtdKYTBWgurbyH+p9uDUgWE4sYjRnB5dM=" crossorigin="anonymous"></script>

Answer №2

When your streams need to complete first before getting the sorted value as a single output, it is recommended to use the forkJoin operator. This operator will wait for Observables to finish and then combine the last values they emitted.

const { of, forkJoin } = rxjs;
const { map } = rxjs.operators;

let a$ = of([1, 8, 10, 4]);
let b$ = of([3, 5, 43, 0]);

forkJoin(a$, b$)
  .pipe(
    map(([a, b]) => [...a, ...b]),
    map(x => x.sort((a, b) => a - b))
  )
  .subscribe(x => {
    console.log('Sorted =>', x);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js" integrity="sha256-mNXCdYv896VtdKYTBWgurbyH+p9uDUgWE4sYjRnB5dM=" crossorigin="anonymous"></script>

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

Exploring property values in an AWS CDK application using Typescript

As a newcomer to the world of Go language, I find myself passing some properties labeled props? to my CDK appstack using the signature: props?: cdk.StackProps When I print the variable props to the console with console.log(props), I see the following expe ...

Dealing with field errors on ajax forms in CakePHP

CakePHP offers a fantastic Error Validation feature where all errors are automatically displayed next to each field in the view. It works flawlessly. However, things get tricky when trying to implement this with Ajax. Is there a way to streamline this pro ...

Trouble with the Sendhub API

I'm currently working with the sendhub API and encountering an error. The error message states that the specified format 'application/x-www-form-urlencoded' does not have a deserialization method available. It is recommended to double-check ...

JS: confidential variables (for safely transmitting a score)

Is it possible to retrieve a randomly generated value declared within an anonymous function (IIFE), and if so, how can it be achieved? (function () { // assuming a complex, obscured random function var salt = random()*10000|0; // assuming an event ...

My objective is to upload a video file and store it on the server using multer

My goal is to effectively receive and save a video file in the uploads folder with the proper extensions using node, express, and multer. Despite successfully passing the video to the server, it doesn't save as intended. Below is my backend code snipp ...

Guide on how to refresh the 'id' after a set period using Ajax technology

I am having an issue with reloading/refreshing a specific table in order to fetch updated database information. The problem is that when I try to refresh only the table, the entire page reloads instead. However, I have managed to identify the 'id&apos ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Achieving this result in HTML using a jQuery accordion component

Hey there, I'm looking to create a full-height accordion that extends from the bottom to the top of the page, similar to what you see on this website: . I also have a footer positioned below the accordion. The content should load when the page loads ...

ShadowCamera is absent in Three.js

I'm currently exploring the world of Three.js and experimenting with this demo code: function init(){ var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, .1, 500); var renderer = new ...

The animation in Rive feels sluggish when navigating to a page with animation in Blazor WASM, despite implementing dispose methods

After attempting to display river animation on the index page using Blazor WASM (basic template), I encountered some performance issues. When navigating back and forth between the Counter page and the index page, I noticed that after around 20 clicks, the ...

"Encountering issues while upgrading Polymer project version from 0.5 to 1.0

I am in the process of upgrading my project from polymer .5 to polymer 1.0. After installing the new version of the polymer library, iron element, and paper element, I encountered the following error: polymer-micro.html:63 Uncaught TypeError: prototype ...

How is it possible for TypeScript to permit an inaccurate comparison like boolean === undefined?

Encountering the peculiar behavior of TS. const isItLanding = false; if (isItLanding === undefined) { // valid return ...; } However, in this instance const isItLanding = 1; if (isItLanding === 'undefined') { // error return ...; } Why do ...

Switch from using a select tag to a check box to easily switch between a dark and light theme

I have implemented a feature on my website that allows users to toggle between dark and light themes using the select tag with jQuery. Here is the code snippet that I am currently using: $(function() { // Code for changing stylesheets based on select ...

Tips for Ensuring the Longevity of my Node.js Server

After developing an application in Node js with express js, I am facing an issue where the server shuts down whenever I close the command prompt. To start the app, I use the following command: c:/myApp > npm start I attempted to resolve this problem b ...

Illumination shining through the depths of three-dimensional shapes

I'm currently working on an HTML project that involves integrating ThreeJs. I have successfully created 4 spheres, with one emitting light and the other three forming a wall. However, I am facing an issue where the spheres behind the wall are still re ...

Manipulating the Document Object Model (DOM) in Google

I typically implement this method to ensure that users adhere to the validation rules before submitting. <a class="waves-effect waves-light btn disabled">Submit</a> But, I recently discovered that by simply removing the disabled class using G ...

Encountering null values in IE8/IE7 JavaScript code

Although I am not a JavaScript expert, I have a simple function that works perfectly in all browsers except for IE8 and 7. function setSelected() { var backgroundPos = $('div.eventJumpToContainer').find('.selected').css('backg ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Error: Calendar tool malfunctioning within duplicated element

Struggling with cloning accordion using a datepicker. Despite researching online, the cloned datepicker is not functioning properly. When the user selects a date from the original datepicker, everything works as expected. However, when the user clicks the ...

Why are my basic style properties not appearing correctly when I use json_encode on an array?

My calendar is written in Javascript within a table with the ID "calendario," allowing me to manipulate it using calendario.rows[i].cells[i]. This calendar lets users make reservations and provides an option to close a day if there are too many reservatio ...