An algorithm designed to categorize data points and display their frequency

Enter the data into the system

[
    {
        “Product”: “Notebook”,
        “Action”: “Add”
    },
    {
        “Product”: “Pen”,
        “Action”: “Sell”
    },
    {
        “Product”: “Pen”,
        “Action”: “Buy”
    },
    {
        “Product”: “Pencil”,
        “Action”: “Sell”
    },
    {
        “Product”: “Pencil”,
        “Action”: “Buy”
    }
]

Desired Result:

[
    {   
        “Product”: “Pen”,
        “sellCount”: 1,
        “buyCount: 1
    },
    {
        “Product”: “Pencil”,
        “sellCount”: 1,
        “buyCount: 1
    }
]

Utilized rxjs functionalities such as reduce and filter.

Answer №1

What are your thoughts on this? I believe there is no need for an external library.

Edit: It could definitely be more organized and avoid using any types, but I wanted to demonstrate it quickly.

Check out the code here

const input = [
  {
    "Item": "Pen",
    "Action": "Sell"
  },
  {
    "Item": "Pen",
    "Action": "Sell"
  },
  {
    "Item": "Pen",
    "Action": "Buy"
  },
  {
    "Item": "Pencil",
    "Action": "Sell"
  },
  {
    "Item": "Pencil",
    "Action": "Sell"
  },
  {
    "Item": "Pencil",
    "Action": "Buy"
  },
  {
    "Item": "Pencil",
    "Action": "Buy"
  }
];

function groupCount(input: any[], keyLabel: string, valueLabel: string) {
  const map: any = {};
  for (const i of input) {
    const key = i[keyLabel];
    if (!map[key]) {
      map[key] = { item: key }
    }
    const countKey = `${i[valueLabel].toLowerCase()}Count`;
    if (!map[key][countKey]) {
      map[key][countKey] = 0;
    }
    map[key][countKey]++;
  }
  return Object.values(map);
}

console.log(groupCount(input, 'Item', 'Action'))

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 combination of Angular2, TypeScript, and moment.js is lacking in terms of available locales (only 'en' is supported)

Currently, I am following a tutorial in a book to grasp the concepts of TypeScript and AngularJS 2.0:(Become_a_Ninja_with_Angular2). In one section, the tutorial walks through creating a custom Pipe and demonstrates an implementation using moment.js. To ...

Having trouble updating $scope after integrating the Parse JS SDK into Angular.js services?

Apologies for any language barriers in my communication. I am currently working on developing a page for reporting current work progress. As part of this task, I have created a function called getWeek() to obtain the current week of the month and store u ...

Splitting a JavaScript string into a two-dimensional array

Can someone assist me with splitting a string into a two-dimensional array? This is an example of my input array: var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla' The desired output array should look like this ...

Verify whether all the elements within a specific div are distinct by utilizing jQuery

I need to create a select box that, when an option is chosen, generates a certain number of textboxes within a div. Currently, there are three fields: display_name[], user_name[], and user_password[] The code for this functionality is as follows: <se ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

Upgrading Xeditable button designs using AngularJS

Have a query. Can you replace the save(submit) button and cancel buttons with links in Xeditable for AngularJS? Appreciate your help ...

Error: NativeScript has encountered difficulty locating the module "@nativescript/schematics"

While attempting to generate a component called "movies" with the command tns generate component movies, I encountered the following error in the terminal log: Could not find module "@nativescript/schematics". I followed the suggestions provided in this G ...

The sharpness of images may diminish when they are created on an HTML5 Canvas within Next JS

I am currently working on a project where users can upload an image onto an HTML5 canvas with fixed dimensions. The uploaded image can be dragged and resized using mouse input while preserving its aspect ratio. Below is the draw function I am using to achi ...

Prevent the need to keep deleting text when entering data into selectize.js <select>_dropdown

I am working with a single choice <select> element that has been enhanced using selectize.js. This <select> element already has an option pre-selected as the current value. To change this value, users must: Click on the drop-down control, Pr ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Unable to submit a post on Ionic 3 platform

I've been attempting to make a POST request using HttpClient Angular to communicate with a server, but I've encountered an error in my code: File: *.ts import { HttpClient } from '@angular/common/http'; constructor(public http: Http ...

Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance. My goal was to create a div that moves back and forth using toggleClass; $('div').on('click', function() { $(this).toggleClass('active') ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

Is there a way to replicate the functionality of $(document).ready for dynamically loaded AJAX content?

$(document).ready(handler) is triggered once the DOM has finished loading. However, if new content containing a $(document).ready(handler) function is added to the page via AJAX, this function will be executed immediately according to the jQuery API. It&ap ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

Importing modules dynamically in NextJS allows for the loading of

I have a basic function that is responsible for loading a script: const creditCardScript = ( onReadyCB, onErrorCB, ) => { let script = document.createElement("script"); script.type = "text/javascript"; script.src = process.CREDIT_CARD_SCRIPT; ...

Execute a function only after the completion of another

I am trying to implement a function where the .hidden class is added to a div only when it has scrolled to the top. I know I can use SetTimeout, but I want to ensure that the div disappears only when it has reached the top of the scroll. $(".more").on(" ...

Slanted lower edge - entire width

Can anyone provide guidance on how to design a div that is 100% width and 300px wide, with a slightly angled bottom border that spans the entire width of the box? https://i.sstatic.net/QSvoQ.png I am open to using either CSS or JavaScript for this task, ...

Creating texture using an array in three.js

I've been experimenting with generating textures from arrays in threeJS but I'm encountering unexpected results. It seems like the method I'm using to generate the texture is incorrect. When I use the texture from the following link, every ...