Tally the number of sub-labels associated with each main label

In my Angular 9 application, I am looking to separate an array based on the lable field. Within each separated array, I would like to determine the count based on the subLable field.

This is the array I am working with:

[
    {"id":1,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"Nice"},
    {"id":2,"socialMediaId":0,"accountId":1,"lable":"Channels","subLable":"Quality"},
    {"id":3,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"poor"},
    {"id":4,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"Nice"}
]

The lable: Application appears 3 times and lable: Channels appears once in the array. I aim to split the array based on the lable as follows:

Application[
    {"id":1,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"Nice"},    
    {"id":3,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"poor"},
    {"id":4,"socialMediaId":0,"accountId":1,"lable":"Application","subLable":"Nice"}
]

Channels[
    {"id":2,"socialMediaId":0,"accountId":1,"lable":"Channels","subLable":"Quality"},
]

To calculate the counts for each unique value in subLable, the final result should be summarized like this:

Application subLable Nice count 2, poor count 1

I have attempted the following code snippet:

this.smdashboardservice.fetchSmDashboardData().subscribe(response=>{
  const lable = response.data.reduce((acc, v) => {
    acc[v.lable] = acc[v.lable] || [];
    acc[v.lable].push(v);
    return acc;
  }, {});

  console.log(lable)
})

Current outcome:

https://i.sstatic.net/kzxS6.png

Answer №1

When grouping by the lable, it is structured similarly to that of a label. The lable contains an object with subLable as the key and an array as the value.

const label = input.reduce((acc, v) => {
    acc[v.label] = acc[v.label] || {};

    acc[v.label][v.subLabel] = acc[v.label][v.subLabel] || [];
    acc[v.label][v.subLabel].push(v);

    return acc;
}, {} as { [key:string]: { [key:string]: any[] } });

The resulting output will look like this:

{
  "Application": {
    "Nice": [
      {
        "id": 1,
        "socialMediaId": 0,
        "accountId": 1,
        "lable": "Application",
        "subLable": "Nice"
      },
      {
        "id": 4,
        "socialMediaId": 0,
        "accountId": 1,
        "lable": "Application",
        "subLable": "Nice"
      }
    ],
    "poor": [
      {
        "id": 3,
        "socialMediaId": 0,
        "accountId": 1,
        "lable": "Application",
        "subLable": "poor"
      }
    ]
  },
  "Channels": {
    "Quality": [
      {
        "id": 2,
        "socialMediaId": 0,
        "accountId": 1,
        "lable": "Channels",
        "subLable": "Quality"
      }
    ]
  }
}

To iterate over the keys of the label object, use a for...in loop. Additionally, employ another for...in loop to iterate over the keys of the label[k] object.

for (let k in label) {
    let msg = `${k} subLabel `;

    for (let subK in label[k]) {
        msg += `${subK} count ${label[k][subK].length} `;
    }

    console.log(msg.trim());
}

Demo @ TypeScript Playground

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

Is there a way for the parent class to access the child class in Angular 2?

Seeking guidance on accessing a child class from a parent class in my Angular 2 application with Typescript. The structure of the parent and child classes are as follows: The parent class, AllDataPageComponent: @Component({ selector: 'all-data-p ...

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

How to use jQuery to maintain an image at the top of a div

Within my HTML, there is a primary root div element containing an image. <div id="root"> <img id="msg"/> </div> Using jQuery, I am able to prepend multiple div elements inside the main root div. However, the problem arises when these ...

Steps to create a continuous blinking/flickering effect on a highchart pathfill

I am currently utilizing highcharts within one of my applications. I want to emphasize a particular stroke based on the content, and while I have achieved this already, I now need it to blink or flicker as if indicating an issue at that specific point. C ...

Exploring the Differences in Site Navigation: PHP/HTML, Ajax, and CSS/Javascript

Lately, I've been weighing the pros and cons of using AJAX for my website navigation to transfer only necessary updated HTML elements. Alternatively, if there isn't a significant difference between new elements and current ones, just loading the ...

What is the best way to retrieve the deviceValue in another function?

currentStatus: string = ""; updateStatus(deviceValue) { this.currentStatus = deviceValue.valueOf(); return this.currentStatus; } update(value: string, index: number, item: number) { this.updateStatus(???); alert(this.currentStatus); ...

What is the method for transforming latitude and longitude coordinates into a physical address for a website?

I'm working with an API that provides latitude and longitude coordinates, and I need to retrieve the address information (city, area, etc.) based on these values. For example, there is a website like where if we enter the IP address of a location, i ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

How come my function does not properly update the visibility of the elements with each subsequent call?

I am currently implementing form validation and updating the display of a notification based on the status code received from an http request with the following code: function checkValidEndpoint() { var xmlHttp = null; var myurl = "/restyendpoint/ ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

Issue arises with library dependencies: various libraries are reliant on distinct versions of a shared library

I have multiple libraries that are dependent on the webpack library. Currently, I am using version 4.79.1, but when I run `npm install` I receive the following warning: [email protected] requires a peer of webpack@^2.0.0 || ^3.0.0 but none is in ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

How can I display base64 image data in a new window without triggering a block?

Currently experiencing challenges with Javascript. Utilizing html2canvas to convert a div to a canvas and then using .toDataURL to convert the canvas to a base64 data stream. Attempting to open base64 image data in a new window, but facing blocks from va ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

What CSS property prevents a fixed header from overlapping a scrolled element?

After creating a fixed header for my HTML table, I noticed that as I scroll down the page, everything is being overlapped by the fixed header except for one slider (noUiSlider). I am curious to know which CSS property is preventing the header from overlayi ...

I am interested in excluding the seconds and milliseconds from my date and time

I currently display my time in the following format: 5:34 PM I only want to show the hour and minute. How can I achieve this? ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...