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

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...

The class type "selectLabel" passed to the classes property in index.js:1 for Material-UI is not recognized in the ForwardRef(TablePagination) component

Just started using react and encountering a repetitive error in the console after adding this new component. Here is the full error message: Material-UI: The key selectLabel provided to the classes prop is not implemented in ForwardRef(TablePagination). ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Child2 ...

Uploading Images to Imgur with Angular 4

As a newcomer to TypeScript, I am faced with the challenge of uploading an image to the Imgur API using Angular. Currently, my approach involves retrieving the file from a file picker using the following code: let eventObj: MSInputMethodContext = <MSIn ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

When using @click as a link, it results in an

I'm attempting to create a clickable row in a datatable that functions as a link. Placing a standard <nuxt-link> within a <td> works fine, but wrapping the entire <tr> disrupts the table layout. Next, I tried using @click with a met ...

Prisma and Next.js: Changes to content require re-deployment for updates to take effect

Just recently, I launched a new website on Vercel. My web application is being built with Prisma and Next.js. However, I'm currently facing an issue where the content doesn't update in real-time unless I manually re-deploy the application. Here&a ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Load a page and sprinkle some contents with a slide effect

I am brand new to jQuery and just starting out, so please excuse me if this question seems basic or silly. I would like the header and footer of my page to stay in place while the center content slides in from the right side when the page loads. This websi ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

Issue with clicking a button in Selenium using JavaScript for automation

I'm encountering an issue where Selenium is detecting an element as disabled, despite it being enabled. To work around this, I am attempting to click on the element using JavaScript with the following code snippet: IWebElement button = driver.FindEl ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Is there a way to assign the chosen option from a dropdown list to an input field in Vue 3?

I am working with a list that is returned from an API request. I have a text input field where I can search for items in the list, and the results are displayed dynamically as I type. My goal is to be able to select an option from the list and display the ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

I'm looking to create a unit test for my AngularJS application

I am currently working on a weather application that utilizes the to retrieve weather data. The JavaScript code I have written for this app is shown below: angular.module('ourAppApp') .controller('MainCtrl', function($scope,apiFac) { ...

Is there a method in TypeScript to create an extended type for the global window object using the typeof keyword?

Is it possible in TypeScript to define an extended type for a global object using the `typeof` keyword? Example 1: window.id = 1 interface window{ id: typeof window.id; } Example 2: Array.prototype.unique = function() { return [...new Set(this)] ...