Utilize Angular ApexCharts to convert data into a visually appealing bar chart display

In my Angular 16 application, I utilized ApexCharts.

The issue I am facing is that my response is not being appended to the chart. Can someone assist me in adjusting the API response?

Response from API:

let data = [
  {
    tenantName: 'OBC+',
    labelName: 'Application',
    total: 85,
    postiveTotal: '21',
    negativeTotal: '64',
  },
  {
    tenantName: 'Discovery-world',
    labelName: 'Application',
    total: 194,
    postiveTotal: '119',
    negativeTotal: '75',
  },
  {
    tenantName: 'OBC+',
    labelName: 'Channels',
    total: 40,
    postiveTotal: '0',
    negativeTotal: '40',
  },
  {
    tenantName: 'Discovery-world',
    labelName: 'Channels',
    total: 59,
    postiveTotal: '0',
    negativeTotal: '59',
  },
];

I need to adjust my response to match this format.

Expected Format:

this.stackedChartData = [
  {
    name: 'OBC Postivie',
    group: 'OBC',
    data: [21, 0],
  },
  {
    name: 'OBC Negative',
    group: 'OBC',
    data: [64, 40],
  },
  {
    name: 'Discovery-world Postivie',
    group: 'Discovery-world',
    data: [119, 0],
  },
  {
    name: 'Discovery-world Negative',
    group: 'Discovery-world',
    data: [75, 59],
  },
];

Although I attempted the following code, it is not functioning correctly.

let labels = [...new Set(data.map((x: any) => x.labelName))];
let subLabels = data.reduce((acc, cur: any) => {
  if (
    acc.findIndex(
      (x) =>
        //console.log(x)
        x.tenantName == cur.tenantName && x.labelName == cur.labelName
    ) == -1
  )
    acc.push({
      tenantName: cur.tenantName,
      labelName: cur.labelName,
      postiveTotal: cur.postiveTotal,
      negativeTotal: cur.negativeTotal,
    });

  return acc;
}, [] as { tenantName: string; labelName: string; postiveTotal: number; negativeTotal: number }[]);

console.log(subLabels);

I plan to implement postiveTotal and negativeTotal with groups of labelName.

Here is a link to my chart demo for reference: link.

Answer №1

You're on the right track with using .reduce() to iterate and transform the array.

Here are the changes you need to make:

  1. The resulting array should be of type

    { group: string; name: string; data: number[] }[]
    .

  2. Check for the presence of the group in the array. If it's not there, add two objects with "Positive" and "Negative" as values.

  3. If the group already exists, find the objects by group and name, then append the value to the data array within the object.

let subLabels = data.reduce((acc, cur: any) => {
  if (
    acc.findIndex(
      (x) =>
        x.group == cur.tenantName
    ) == -1
  ) {
    acc.push({
      group: cur.tenantName,
      name: cur.tenantName + ' Positive',
      data: [Number(cur.postiveTotal)],
    });

    acc.push({
      group: cur.tenantName,
      name: cur.tenantName + ' Negative',
      data: [Number(cur.negativeTotal)],
    });
  } else {
    let groupPositive = acc.find(
      (x) =>
        x.group == cur.tenantName && x.name == cur.tenantName + ' Positive'
    );

    groupPositive.data.push(Number(cur.postiveTotal));

    let groupNegative = acc.find(
      (x) =>
        x.group == cur.tenantName && x.name == cur.tenantName + ' Negative'
    );

    groupNegative.data.push(Number(cur.negativeTotal));
  }

  return acc;
}, [] as { group: string; name: string; data: number[] }[]);

this.stackedChartData = subLabels;

See Demo on StackBlitz

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

retrieve information from Angular service

Is there a way for parent components to communicate with child components by injecting providers directly into the TypeScript file of each child component? I am trying to retrieve data using get and set methods, but I am unsure how to proceed. Any suggesti ...

What method could I use to verify that my Angular 2+ login function has been invoked successfully?

Can anyone provide guidance on how to effectively verify if a function has been executed within the interaction of a component and a service? I welcome any insights or suggestions that can help me address this challenge! ...

The arrow keys (up and down) are unresponsive when using mat-table in an Angular application

There seems to be an issue with my code. When I press the down arrow key for the first time, it goes to the next row as expected. However, when I press the down arrow key again, it does not function properly. (https://i.stack.imgur.com/4qznx.jpg) **HTML* ...

The click method in the Angular unit test does not seem to be executing successfully

I'm facing a seemingly simple issue where I am unable to confirm that a click handler is being triggered on my component. header.component.ts import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selecto ...

The error encountered is: "Unable to modify the 'x' property as it is readonly for the '[object Array]' object."

I've attempted various methods to modify this problem, regardless of how it's explained on different Stack Overflow threads. I am faced with an obstacle where I have an array composed of objects, and my goal is to iterate through the array and mo ...

The element 'app-layout' is unrecognized: a guide to sharing Components across multiple Modules

Everything was running smoothly with my application until I made the decision to implement lazy loading: As a result, my shared component appears like this: import { Component, Renderer2 } from '@angular/core'; export interface FormModel { ...

Ionic Error: spawn UNKNOWN_PROCESS

Upon attempting to execute the following command: ionic serve --cordova --platform browser An error message was displayed: Error: spawn UNKNOWN at ChildProcess.spawn (internal/child_process.js:403:11) at Object.spawn (child_process.js:553:9) at spawn ( ...

Is there a way to program a function that can automatically trigger or refresh an HTTP POST method?

How can I create a method in a distant component that will run a POST request when a button is clicked? I believe I need to use a service in this situation. It's not necessary for it(this.qwe) to be in the constructor, it's just an example... ...

What is the method for obtaining distinct hover-over values for individual items within a dropdown menu?

If utilizing angular2-multiselect-drop down, what is the correct method to obtain distinct hover over values for individual items in the drop down? When dealing with standard HTML, you can directly access each element of the drop down list if it's ha ...

Using React's Ref to handle conditional rendering and handling the case when

I am facing an issue with my React ref animationRef being null when I conditionally render an element. It works perfectly fine outside of the condition, but not within it. Is there a way to ensure that the ref has a value even when conditionally renderin ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Prevent external scrolling while Bootstrap modal is active

<div class="modal mt-5p" role="dialog" [ngStyle]="{'display':IONotes}"> <div class="modal-dialog modal-md mt-0px width-70p"> <div class="modal-content" style="height:500 ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Halting the execution of a function if a new call is made within a 500ms timeframe

I am looking to enhance this code by implementing a feature that introduces a timer of 500ms whenever the onValueChange function is triggered. If the function is called again within those 500ms, it should restart the execution of the previous call. Code p ...

The functionality of Flowbite Drawer is disabled when used within an ngFor loop in Angular

Currently, I am utilizing Flowbite () as a Tailwind CSS plugin in my Angular project. Everything is functioning perfectly except for an issue that arises when I try to call a drawer button within a table generated using ngFor. Unfortunately, I am at a los ...

Issue with triggering angular function multiple times in certain conditions

Issue: Experiencing difficulties with Angular directive as it is being called multiple times, resulting in incorrect transaction outcomes and multiple entries on the Console screen. Desired Outcome: Ensure that the function executes only once. Sample cod ...

What is the best way to transform an array containing double sets of brackets into a single set of brackets?

Is there a way to change the format of this list [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]] to look like [" ", " ", " &qu ...

Incapability of Rearranging Rows in a Group using Row Drag feature in ag-Grid for Angular

Having some trouble with ag-Grid in my Angular project. Specifically, I'm having issues reordering rows within a group using the row drag feature. If you want to take a look at the code snippet causing problems, it's available on CodeSandbox. I ...

Invoke a general function with corresponding generic parameters

I am currently working on a function that takes another function and its arguments as parameters, then runs the function with the provided arguments and returns the result while maintaining the data types. If the function being provided has a fixed return ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...