Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows:

[{
   "_id": 1,
   "_title": "Test Event 1",
   "_startDate": "2019-05-29T07:20:00.000Z",
   "_endDate": "2019-05-29T08:00:00.000Z",
   "_isAllDay": false
 }, {
   "_id": 2,
   "_title": "Test Event 2",
   "_startDate": "2019-06-10T07:00:00.000Z",
   "_endDate": "2019-08-02T07:00:00.000Z",
   "_isAllDay": false
 }, {
   "_id": 3,
   "_title": "Test Event 3",
   "_startDate": "2019-06-12T07:00:00.000Z",
   "_endDate": "2019-06-12T10:00:00.000Z",
   "_isAllDay": false
}]

I need to transform this array into a two-dimensional array grouped by the month of the start date (using moment.js Objects). The desired format is as follows:

[{
        "May 2019": [
            [
                "_id": 1,
                "_title": "Test Event 1",
                "_startDate": "2019-05-29T07:20:00.000Z",
                "_endDate": "2019-05-29T08:00:00.000Z",
                "_isAllDay": false
            ]
        ]
    },
    {
        "June 2019": [
            [
                "_id": 2,
                "_title": "Test Event 2",
                "_startDate": "2019-06-10T07:00:00.000Z",
                "_endDate": "2019-08-02T07:00:00.000Z",
                "_isAllDay": false
            ],
            [
                "_id": 3,
                "_title": "Test Event 3",
                "_startDate": "2019-06-12T07:00:00.000Z",
                "_endDate": "2019-06-12T10:00:00.000Z",
                "_isAllDay": false
            ]
        ]
    }
]

The code I have tried so far is not giving me the expected output:

// Observable<Event[]> is returned by a function
.pipe(groupBy((events: Event[]) => events.map((event: Event) => event.startDate.format('MMMM YYYY')), (events: Event[]) => events.map((event: Event) => event.startDate.format('DD/MM/YYYY'))),
mergeMap(group => zip(of(group.key), group.pipe(toArray())))
.subscribe((data) => { 
      console.log(data); 
});

This is the current output from the code mentioned above:

[
  [May 2019, June 2019, June 2019], 
  [
    [29/05/2019, 10/06/2019, 12/06/2019]
  ]
]

Any insight on how to achieve the desired grouping would be much appreciated. Thank you!

Answer №1

Here are some steps you can take -

const data = [{
   "_id": 1,
   "_title": "Test Event 1",
   "_startDate": "2019-05-29T07:20:00.000Z",
   "_endDate": "2019-05-29T08:00:00.000Z",
   "_isAllDay": false
 }, {
   "_id": 2,
   "_title": "Test Event 2",
   "_startDate": "2019-06-10T07:00:00.000Z",
   "_endDate": "2019-08-02T07:00:00.000Z",
   "_isAllDay": false
 }, {
   "_id": 3,
   "_title": "Test Event 3",
   "_startDate": "2019-06-12T07:00:00.000Z",
   "_endDate": "2019-06-12T10:00:00.000Z",
   "_isAllDay": false
}];

from(data).pipe(
  groupBy(d => d['_startDate'], p => p),
  mergeMap(group => zip(of(group.key), group.pipe(toArray())))
).subscribe(console.log);

Take a look at the following stackblitz for more details -

https://stackblitz.com/edit/rxjs-groupby-key-vals-hsj3a7?file=index.ts&devtoolsheight=100

You may need to customize the date format to suit your requirements.

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 concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

No value found for Req.file using the express-fileupload and multer libraries

I have exhausted all possible scenarios and attempted various variations and methods recommended in the documentation and from other sources like Stack Overflow. However, none of them seem to work -> I constantly receive req.file is: undefined Here is ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

What's the best way to add a timestamp and class name to Angular's $log for an enhanced logging experience?

Is there a way to customize Angular logs by adding a timestamp and classname? For example: $log.info('this log entry came from FooBar'); "9:37:18 pm, FooBar: this log entry came from FooBar" I've come across various examples online that ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

Derive data type details from a string using template literals

Can a specific type be constructed directly from the provided string? I am interested in creating a type similar to the example below: type MyConfig<T> = { elements: T[]; onUpdate: (modified: GeneratedType<T>) => void; } const configur ...

Function returning undefined when accessing prototype property in JavaScript

When attempting to create an image rotator using prototypal inheritance, I am encountering an error in the console showing: TypeError: this.curPhoto is undefined this.curPhoto.removeClass('previous'); I have placed this code in the callb ...

Attempting to switch between classes with the click of a button

I am attempting to create a basic animation that involves changing an image from A to B to C when a button is clicked. However, I am encountering an issue with the error message Cannot read properties of undefined (reading 'classList'). I am puzz ...

Plugin initialization cannot occur as the $scope DOM elements are still dynamic and not ready

As I venture into the realm of AngularJS, this project marks my first deep dive into building something substantial, despite having only tinkered with a few tutorials and demos. Bear with me if I struggle to articulate what may be a straightforward questio ...

The request included an unsupported media type of "text/plain;charset=UTF-8". This caused an error in the NextJS API when interacting with Django Rest Framework

Currently diving into the world of web development, I am endeavoring to construct a website utilizing NextJS and Django Rest Framework. While NextJS effectively proxies API endpoints for retrieving data, I find myself grappling with making it work for a PO ...

How Can You Change the Position of a Threejs Vector3?

I'm attempting to create bones and then manipulate the vertices of each bone, but I am struggling with the correct syntax. Here is an example of what I have tried: var v = new THREE.Vector3(0,0,0); var b = new THREE.Bone(); b.position.x = 5; b.positi ...

You can interact with our dropdown menu using the tab key, even when it is

We are looking to make our dropdown tabbable when expanded and non-tabbable when collapsed. We attempted using tabindex="-1" on the content inside the expandable div, but this resulted in it being non-tabbable even when expanded. Any suggestions on how t ...

What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully upd ...

Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements. In my model, I have a name and options, both of which are strings. This is what I currently have: const myArrayToDuplicate = [myModel, myModel, myModel] My ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

What is the best way to say hello using jQuery?

I need some assistance with a task that involves entering my name into an input field, clicking a button, and having an h1 tag display below the input saying Hello (my name)! Unfortunately, I am struggling to figure out how to achieve this. Below is the H ...

Crawlers designed to handle websites with never-ending scroll feature

Currently seeking a crawler application that can analyze the JavaScript on a webpage for AJAX requests and identify functions that initiate those calls in order to retrieve all content from start to finish. I would develop this myself, but my workload is ...

Apps created with PhoneGap will maintain the original sizing of web pages and not automatically resize for display on Android devices

After successfully porting my web-based tool to Android using PhoneGap from my Github repository, I encountered an issue with the display on Android devices. The app loads up too big for the screen, forcing me to constantly scroll around to see and access ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...