Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format):

[
  {
    "name": "john",
    "lastName": "doe",
    "gender": "male"
  },
  {
    "name": "jane",
    "lastName": "doe",
    "gender": "female"
  },
  {
    "name": "peter",
    "lastName": "dickons",
    "gender": "male"
  },
  {
    "name": "eva",
    "lastName": "dickons",
    "gender": "female"
  },
]

To group these objects by their last name, the following code can be used:

const groupByObjectKey = (users: User[], key: string): any => {
    return users.reduce((rv: any, x: any) => {
        (rv[x[key]] = rv[x[key]] || []).push(x);

        return rv;
    }, {});
};

const usersGroupedByLastName = groupByObjectKey(
    users,
    "lastName"
);

If you want to group them not only by last name but also by gender using the same function, you can do so as follows:

const groupByObjectKey = (users, key) => {
  return users.reduce((rv, x) => {
    (rv[x[key]] = rv[x[key]] || []).push(x);

    return rv;
  }, {});
};

let users = [{
    "name": "john",
    "lastName": "doe",
    "gender": "male"
  },
  {
    "name": "jane",
    "lastName": "doe",
    "gender": "female"
  },
  {
    "name": "peter",
    "lastName": "dickons",
    "gender": "male"
  },
  {
    "name": "eva",
    "lastName": "dickons",
    "gender": "female"
  },
];

const usersGroupedByLastName = groupByObjectKey(
  users,
  "lastName"
);

console.log(usersGroupedByLastName);

Answer №1

If you want to enhance the groupByObjectKey function to accept an array of keys instead of just one key, you can follow this example:

function groupByMultipleKeys(dataArray: Item[], keysArray: string[]): any {
    return dataArray.reduce((result: any, item: any) => {
        const compoundKey = keysArray.map(key => item[key]).join('-');
        (result[compoundKey] = result[compoundKey] || []).push(item);
        
        return result;
    }, {});
}

const itemsGroupedByTypeAndColor = groupByMultipleKeys(
    items,
    ['type', 'color']
);

This function will group the items based on multiple keys like type and color, creating a unique key by combining the values of the specified keys with a separator.

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 it possible to utilize the NavigationTimingAPI with asynchronous requests?

Currently, I am working on implementing performance measuring functionality in our project that utilizes custom elements v1. The NavigationTimingAPI provides detailed measurements for various navigation types (navigate, reload, browser back/forward): Is ...

Maximize the performance of displaying images

At the moment, I have a set of 6 graphics (0,1,2,3,4,5)... The arrangement of these graphics looks fantastic! However, I am facing an issue when a user only has 3 graphics, for example 0, 2, and 5. In this scenario, my graphics do not line up correctly. D ...

Is there more to AJAX than just fetching a JSON file?

I am in need of using AJAX to achieve my goal. My aim is to have the content of specific subpages displayed in the HTML markup below when a particular link in a list is clicked. This data can be readily accessed from the database via the CMS's API (I ...

Why is the dateclick event in PrimeNG's FullCalendar not being emitted when clicking on a date? What is the best way to handle click events on specific dates within the calendar?

I am new to using Angular and PrimeNG, and I am facing challenges while trying to implement the FullCalendar component. The specific component I am referring to can be found here: The issue arises when I attempt to trigger an event when a user clicks on a ...

How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click eve ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

JavaScript: Increasing the date by a certain number of days

I've been researching various topics and so far, I haven't come across one that addresses my specific issue. Here's the task at hand: 1) Extract a bill date in the mm/dd/yy format, which is often not today's date. 2) Add a dynamic ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

Is it possible for Jaydata relationships to function seamlessly without the need to be

I am attempting to set up a basic model with Parent -> Child relationships (correctly declared and functioning, I believe). This is my approach: var parent = new $data.Types.Parent(); $data.context.Parents.add(parent); parent.Code = 123; var child = ...

When utilizing create-next-app, an error may occur stating that the produced JSX.Element cannot be assigned to a variable

After creating a new project with TypeScript using create-next-app, I encountered an error in the default homepage when opened in my IDE (WebStorm). The error message reads: "Initializer type () => JSX.Element is not assignable to variable type NextPa ...

Checking for the winner in a JavaScript tic-tac-toe game

Here is the code snippet for a tic-tac-toe game: $(".square").one("click", function() { if( gameOver == false ) { sq1 = $("#sq1").text(); // captures the value of squares after being clicked. sq2 = $("#sq2").text(); //and so on for all 9 squares } / ...

Setting the row ID value after performing form editing in free jqGrid

In the table, there is a primary key with 3 columns (Grupp, Kuu, Toode), and the server returns an Id created from those columns. When the primary key column is changed in form editing, the server sends back a new row id. However, Free jqgrid does not se ...

Leverage the power of function overloading in TypeScript for efficient code

How can function overloading be reused effectively in TypeScript? Consider a scenario where a function is overloaded: function apply(value: number): number; function apply(value: string): string; function apply(value: any): any { return value; } No ...

How do you send a variable in a GET request with React?

My challenge is to retrieve data from a table where the teacherId matches the teacherId of the user who logs in, but I am facing difficulties in passing this teacherId from the front-end to the back-end. Below is the backend code: app.get("/api/get&q ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...

Having trouble executing my Node.js project written in Typescript due to an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION] - the file extension ".ts" for /app/src/App.ts is unrecognized

After attempting to launch my application on Heroku, I encountered the following stack trace. The app is a basic ts.app using ts-node and nodemon. I am eagerly awaiting the solution to this issue. 2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting p ...

Set the HTML content as a string in the Html variable, similar to innerHTML but without using JavaScript directly from an external

When working in an embedded ruby (html.erb) file, I encounter a situation where I have a string of HTML such as variable_string = "<p>Some <strong>Content</strong></p>". In JavaScript, we can easily update the DOM with Element.inn ...

JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substr ...

Acquiring the appropriate type from a type object using generics in TypeScript

I am working with an enum export const trackingKeys = { Form: 'form', Video: 'video', } as const I also have a type that assigns a type property to each key export type TrackingPropertiesByKey = { [trackingKeys.Form]: { bar : num ...