Acquire a specified number of items from every category using TypeScript

I need to extract N items from each group within a list using Typescript. In C# with LINQ, I would achieve something similar like this but I am unsure of the equivalent in TypeScript.

var rr = db.Products.GroupBy(x => x.ProductSubTypeCategoryId).Select(g => new { GroupName = g.Key, Items = g.Take(4).ToList() });

My model is

const lstTrade : Trade [] = [
  { contractName: 'Contract1' ,amount : 12}, 
  { contractName: 'Contract1' ,amount : 12},
  { contractName: 'Contract1' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20}
];

Now, I have a list of Trade items and my goal is to retrieve only 2 items from the list with unique contract names. Specifically, two items with "Contract1" and two items with "Contract2".

Answer №1

Shanon's answer may be correct, but it only covers the group by part of the code. I will provide two examples - one for GroupBy and one for Take - that can help resolve your issue.

I want to clarify that the GroupBy and Take examples I am sharing are not my own. Credit should be given to this website . This resource can assist with various LINQ tasks in JavaScript (note: working with Arrays in TypeScript involves using JavaScript).

GroupBy

C#

var result = persons.GroupBy(person => person.lastname);

TypeScript

let result = persons.reduce((previous, person) => {
    (previous[person.lastname] = previous[person.lastname] || []).push(person);
    return previous;
}, []);

Take

C#

var result = persons.Take(2);

TypeScript

let result = persons.slice(0, 2);

For your specific scenario, you can follow this approach:

const lstTrade : Trade [] = [
  { contractName: 'Contract1' ,amount : 12}, 
  { contractName: 'Contract1' ,amount : 12},
  { contractName: 'Contract1' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20}
];

let result = lstTrade.reduce((previous, trade) => {
    (previous[trade.contractName] = previous[trade.contractName] || []).push(trade);
    return previous;
}, [])
// The result is now an object with groupedTrades as properties. To limit the items in each group, do the following:
for (const groupName in result) {
    result[groupName] = result[groupName].slice(0, 2);
}

Answer №2

When it comes to working with Arrays and Collections in any programming language, the use of reduce is key for solving array-based problems effectively. In this example, the array has been transformed into an object where items are grouped by their contractName. This allows for easy access and manipulation of the data.

const lstTrade = [
  { contractName: 'Contract1' ,amount : 12}, 
  { contractName: 'Contract1' ,amount : 12},
  { contractName: 'Contract1' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20},
  { contractName: 'Contract2' ,amount : 20}
];


const intoObject = lstTrade.reduce<Record<string, typeof lstTrade>>((grouped, curr) => {
  return {...grouped, [curr.contractName]: (grouped[curr.contractName] || []).concat(curr)}
}, {})

/*
{
    Contract1: [{contractName: 'Contract1, amount: 12'}, {contractName: ....}...]
    Contract2: [...]
}
*/

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

Align the object with the path it is following

Currently, I am in the process of learning about vectors and their application in moving objects within ThreeJS. For an experiment, I am propelling a box using a specified velocity and an arbitrary gravity vector. Additionally, I am attempting to align th ...

Concealing a button once the collapse feature is toggled in Bootstrap

The following code snippet from the bootstrap website demonstrates how to use collapse functionality: <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Link with href & ...

"Strategies for effectively utilizing the .find method to locate specific users within a database

I'm currently working on developing a User Authentication system, but I've hit a roadblock when it comes to verifying users. Specifically, I'm struggling with understanding how to iterate through all of my users in order to filter out their ...

Preserve the authentic picture along with a blur mask that can be dragged and applied to it

Is there a way to preserve the original image while having a draggable blur mask over it? If you want to see an example of a draggable blur mask over an image, you can check out this link: https://codepen.io/netsi1964/pen/AXRabW $(function() { $("#ma ...

Looks like an error has occurred: "Swal has not been defined"

I'm currently working on a small project that involves using CodeIgniter, VueJs, and the Sweet Alert Javascript library. However, I encountered an error in my console stating ReferenceError: "Swal is not defined" when I try to call swall.fire({}) with ...

Can you delve into the origin of the term Modal in the context of Angular and web development?

My understanding of a Modal is that it is a webpage component that opens separately from the main page in order to maintain continuity. Am I correct? I am curious as to why it is referred to as a Modal. Could it be short for modularity? Meaning that vari ...

Steer clear of 405 errors by implementing AJAX in combination with Flask and JINJA templ

Hey there, I'm fairly new to backend work so please bear with me. I've been doing some research but haven't found the answer yet. Currently, I'm working on an application that fetches search results from a 3rd party API. I'm tryi ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...

Disabling dynamic color updates upon refresh

I am currently using chartjs and I want to generate new random colors each time the page is refreshed. However, I need these colors to remain fixed and not change after a page refresh or reload. Below is the function I am working with: getRandomRgb() { ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

Is there a way to utilize Angular in identifying whether a given value corresponds with the value of a particular radio button within my application?

I have an array of lists that I need to display in radio buttons. Like this: https://i.stack.imgur.com/cmYgO.png https://i.stack.imgur.com/Zx4bm.png https://i.stack.imgur.com/jBTe3.png My goal is to have a checkbox that matches the values loaded from a ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Passing data through Angular2 router: a comprehensive guide

I am currently developing a web application with the latest version of Angular (Angular v2.0.0). In my app, I have a sub-navigation and I want to pass data to a sub-page that loads its own component through the router-outlet. According to Angular 2 docume ...

What is the process of including assetlinks.json in an Angular project to enable Android App Links?

Hey everyone, I could really use some assistance! I'm unsure about the specific directory to place the assetlinks.json file and what additional information needs to be included for it to function properly. I do have a SHA256 key and applicationId, so ...

Sending the :id parameter to the Service component

In the early days of my Angular journey, I have a simple question. Currently, I am utilizing the WordPress REST API to showcase a list of posts from a specific category by using posts?categories={ID HERE}. However, I am facing an issue in passing the ID f ...

Expanding MaterialUi styled components by incorporating TableCellProps: A guide

When trying to create a styled TableCell component in a separate file, I encountered an error in TypeScript (ts(2322)). TypeScript was indicating that the properties "component," "scope," and "colSpan" could not be used because they do not exist in StyledC ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

What is the best way to set up Observables in Angular's strict mode?

Incorporating Angular strict mode into a project that heavily relies on observables in controllers and templates has led to a debate among colleagues on how they should be initialized. Two main approaches were discussed: 1. public obj$: Observable<MyOb ...

Having issues with my Angular directive not receiving data from the controller

I am encountering an issue with my controller .controller('Main', ['$scope', function ($scope) { $scope.uiState = {'name': 'test'}; }]) My directive is structured as follows scope: {uiState: '=& ...

The endpoint /api/user does not allow POST requests

I'm currently testing a user registration route and encountering a "Cannot POST /api/user" error. Although I can successfully make a GET request using Postman, the issue arises when trying to make a POST request. Any help or guidance on pinpointing t ...