What are the steps for transforming my 2D array to fit a specific schema using RxJS?

UPDATE I stumbled upon a potential solution that I have appended to my question and am now seeking a more refined approach.

In the context of an Angular 9 application, I am working with a two-dimensional array that I need to restructure. Through my use of RxJS operators, I have achieved some degree of success in this task.

The objective is to group all the data with the property _id by their respective row numbers under a parent level property called dataset. Additionally, I aim to include properties such as iconDefault and row.

While I can achieve this goal using traditional looping techniques, I want to leverage RxJS further for a better understanding.

This is my initial 2D array:

[
  [
    {
      "_id": "5efbb97e80752985301c3447",
      "row": 1,
      "position": 0,
      "tab": 1
    },
    {
      "_id": "5efbb97e80752985301c3453",
      "row": 1,
      "position": 1,
      "tab": 1
    }
  ],
  [
    {
      "_id": "5efbb97e80752985301c3411",
      "row": 2,
      "position": 0,
      "tab": 1
    },
    {
      "_id": "5efbb97e80752985301c3414",
      "row": 2,
      "position": 1,
      "tab": 1
    },
    {
      "_id": "5efbb97e80752985301c33f3",
      "row": 2,
      "position": 2,
      "tab": 1
    }
  ],
  [
    {
      "_id": "5efbb97e80752985301c343b",
      "row": 3,
      "position": 0,
      "tab": 1
    }
  ]
]

The desired end result:

{
    "tab": 1,
    "dataset": [{
        "row": 1,
        "iconDefault": "5e7824c67bd78eb199e95f3e",
        "ids": ["5efbb97e80752985301c3447",
            "5efbb97e80752985301c3453"
        ]
    }, {
        "row": 2,
        "iconDefault": "5e7824c67bd78eb199e95f3e",
        "ids": ["5efbb97e80752985301c3411",
            "5efbb97e80752985301c3414",
            "5efbb97e80752985301c33f3"
        ]
    }, {
        "row": 3,
        "iconDefault": "5e7824c67bd78eb199e95f3e",
        "ids": ["5efbb97e80752985301c343b"]
    }]
}

The best current outcome I could generate:

{
  "dataset": [
    [
      "5efbb97e80752985301c3447",
      "5efbb97e80752985301c3453"
    ],
    [
      "5efbb97e80752985301c3411",
      "5efbb97e80752985301c3414",
      "5efbb97e80752985301c33f3"
    ],
    [
      "5efbb97e80752985301c343b"
    ]
  ],
  "tab": 1
}

I have defined the source 2D array and applied the following code to produce my existing output

  // source defined from 2d array shown above
  let updatePackage = {};
  updatePackage.dataset = source.map((subarray) =>
     subarray.map((row) => row._id)
  );
  updatePackage.tab = 1; //manually set but ideally obtained from relevant data
  console.log(updatePackage);
  document.body.append(JSON.stringify(updatePackage));

Example on JSFiddle

An alternative solution based on OCD tendencies:

let updatePackage = {} as any;
        updatePackage.tab = 1;
        let dataset = [] as any;
        dataset = this.rows.map((subarray) => subarray.map((row) => row._id));
        updatePackage.dataset = dataset.map((row, rowIndex = 0) => {
          rowIndex++;
          return {
            row: rowIndex,
            ids: row,
            iconDefault: '5e7824c67bd78eb199e95f3e',
          };
        });

JSFiddle showcasing the OCD Solution

Answer №1

Let me share my method:

src$.pipe(
  // When `src$` emits `[[a, b], [c, d]]`,
  // using `mergeAll` will separate them into `[a, b]`, `[c, d]`
  mergeAll(),

  // It could be useful to remove empty arrays
  filter(arr => arr.length !== 0),

  map(
    arr => arr.reduce(
      (acc, crt) => (acc.ids.push(crt._id), acc), 
      { iconDefault: "5e7824c67bd78eb199e95f3e", ids: [], row: arr[0].row }
    )
  ),

  scan(
    (acc, crt) => (acc.dataset.push(crt), acc),
    { tab: 1, dataset: [] },
  )
)

If you need to adjust the tabs management, some logic modifications may be necessary.

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 steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

Issue with sx prop type error found in the TabPanel component of MUI v5

My first time using MUI with TypeScript has hit a roadblock with the new sx prop. Check out the error displayed by TypeScript in the screenshot linked below: https://i.sstatic.net/JYDTX.png Interestingly, the error only pops up on the TabPanel Component, ...

Guide on how to focus on a specific node programmatically within a PrimeNG Tree component

One of the features of PrimeNG is the ability to scroll to a specific TreeNode: To implement this in html: <p-tree #mytreeid id="mytree"></p-tree> In an Angular application: @ViewChild("mytree") mytree: Tree; // selection represents the Tre ...

What is behind the inconsistency of RxJS versions?

Trying to set up a node/angular2 solution on cloud9 has been quite the challenge. Below is my package.json: { "name": "example", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www", "postinstall": "typings install", ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

While trying to update Angular 5 to 6, I am encountering an incompatible peer dependency error when utilizing the ng update @angular/core command

I have been encountering issues while trying to upgrade my Angular app from version 5 to version 6 by following this guide. After successfully running the commands below: npm install -g @angular/cli npm install @angular/cli ng update @angular/cli An err ...

Running frontend and backend applications together in a Docker container

As I work on integrating my frontend in Angular with the corresponding backend in Spring Boot, both as standalone projects, I am now looking to transition them into production mode. This has led me to consider hosting each project in separate docker contai ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Instructions for obtaining the most recent event using the `fromEvent` function

I'm having trouble capturing the final event generated by the keyup event using rxjs. Every time, my console is filled with multiple log messages. Here's the Angular directive I'm working with: import { Directive, AfterContentChecked, Eleme ...

What is the process for adjusting the color of axes in vue-chartjs?

Seeking help on how to adjust the color of the axis in my graph. Has anyone encountered a similar issue before? The chart I'm working with resembles the one shown in the image. Not sure if this issue is related to it being a time graph. Below is the V ...

Is there a way to both add a property and extend an interface or type simultaneously, without resorting to using ts-ignore or casting with "as"?

In my quest to enhance an HTMLElement, I am aiming to introduce a new property to it. type HTMLElementWeighted = HTMLElement & {weight : number} function convertElementToWeighted(element : HTMLElement, weight : number) : HTMLElementWeighted { elemen ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

What might be causing the excessive margins in my Bootstrap grid layout?

I've recently integrated Bootstrap into my Angular project using npm, but I'm facing an issue with excessive margins on the sides. Can anyone provide assistance? Below is the code snippet: <div class="container"> <div class="row"> ...

Navigating to a different page in Ionic 2 upon app initialization

Is there a way to automatically redirect the page to the home page instead of displaying the login page if there is already a token stored in localStorage? I currently have the following code in the constructor() of app.component.ts, but it still display ...

In the context of Angular applications, how can a state be defined?

Exploring the world of NgRx for the first time and diving into its documentation, I stumbled upon this statement: "State is a single, immutable data structure." In plain terms, what exactly does "state" refer to? Can you provide some basic examples to ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Can a class be passed to the binding attribute in Angular framework?

We currently have a system in place that is dependent on a numeric value being set to either 1 or 2 in order to display specific icons. This method is functional. <span *ngIf="config.icon" [class.fas]="true" [class.fa-plus]="icon===1" ...

Issue with Angular 2 AOT Compilation when trying to access formArray

This is the formGroup I created this.createOrderForm = this.fb.group({ items: this.fb.array([]) }); To add an item on button click addItem() { const control = <FormArray>this.createOrderForm.controls['items']; const a ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...