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

Guide on implementing findOne for name validation in Node.js using data from MongoDB

Can someone help solve the issue of name duplication and provide guidance on how to execute the codes in Postman API? The attached codes can be found below: *employeemodel.js enter image description here *employeecontroller.js enter image description her ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Ensuring the selected date matches any consecutive dates within the dates array in Angular

Imagine if 01/01/2022 is chosen from the input field, and my array of dates looks something like this: ['31/12/2021', '01/11/2021', '02/01/2022'...] In this scenario, when '31/12/2021' and '02/01/2022' are ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Tips on passing an object as data through Angular router navigation:

I currently have a similar route set up: this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id]) The navigation is working fine, but I would like to pass the entire data object to the screen in order to render it using the route. How can ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

"Error: The dist directory is missing in the Angular Docker File

I am in the process of Dockerizing an Angular project and here is my Dockerfile: # 1. Building the Angular app using Node.js FROM node:12 as builder WORKDIR /app COPY package.json package-lock.json ./ ENV CI=1 RUN npm ci COPY . . RUN npm run build-web -- ...

The Angular2 application encountered a 404 file not found error while trying to read a Const from a ts

Recently I started working with angular2 and encountered a problem when trying to access constant values from an external .ts file using the following code: import {apis} from '../constants/apis'; The content of the constants/apis.ts file is as ...

My project in WebStorm encounters a setback due to the updated release of Typescript 5+

Recently, I had to upgrade my TypeScript version from 4.9.5 to 5.1.3 because one of the libraries I'm using made a fix that required a newer TypeScript version. After the update, TypeScript started throwing errors for console calls and React event di ...

Tips for verifying the connections between an Angular application and Azure Function (negotiate) when integrating with Azure SignalR Service

I'm working on an angular application that is authenticated with Azure AD, connecting to an Azure Function (negotiate) which then communicates with Azure SignalR service using specific keys. I am looking for guidance on how to authenticate requests ma ...

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

Retrieve information from an axios fetch call

Having an issue with the response interface when handling data from my server. It seems that response.data.data is empty, but response.data actually contains the data I need. Interestingly, when checking the type of the last data in response.data.data, it ...

Effortlessly control your CSS within extensive Angular 2/4/5 projects

When working in Angular, I typically organize my CSS on a component basis with some global styling in styles.css. However, I'm looking for a better way to easily update CSS in the future. I want to be able to make changes in one place and see them ref ...

What is the best approach for designing a UI in Angular to showcase a matrix of m by n dimensions, and how should the JSON format

click here for a sneak peek of the image Imagine a matrix with dimensions m by n, containing names on both the left and top sides. Remember, each column and row must be labeled accordingly. ...

Utilizing ternary operators in Angular 6 tables

I need to dynamically display certain amounts based on the comparison of two interest values. Here is the logic: <td *ngIf="subTable.flexitaxMaxPaymentDate"> subTable.flexitaxMaxInterest > subTable.IRDInterest ? {{subTable.maxAmou ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Strategies for efficiently loading 100,000 records into a table using Spring Boot on the server side and Angular on the front end

I am facing an issue with the speed of loading data from the back end to the front end without causing delays on the client side. I am using Spring Boot for the back end and Angular 7 for the front end. The problem arises when I submit a request from the f ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...