Custom groupBy function for arrays in TypeScript

Below is an example of an array:

[
 {
   "exam" : "1",
   "class": "1A1",
   "rooms": "245",
   "teachers": "A"
 },
 {
   "exam" : "1",
   "class": "1A2",
   "rooms": "685",
   "teachers": "B"
 },
 {
   "exam" : "2",
   "class": "1EM1",
   "rooms": "630",
   "teachers": "C"
 }
]

How can I transform it into the following format? I attempted to use lodash's groupBy method but did not achieve the desired outcome.

[
 {
   "exam" : "1",
   "classes": [
     {
       "class": "1A1",
       "rooms": "245",
       "teachers": "A"
     },
     {
       "class": "1A2",
       "rooms": "685",
       "teachers": "B"
     }
   ]
 },
 {
   "exam" : "2",
   "classes": [
     {
       "class": "1EM1",
       "rooms": "630",
       "teachers": "C"
     }
   ]
 } 
]

Answer №1

let data = [
    {
        "exam": "1",
        "class": "1A1",
        "rooms": "245",
        "teachers": "A"
    },
    {
        "exam": "1",
        "class": "1A2",
        "rooms": "685",
        "teachers": "B"
    },
    {
        "exam": "2",
        "class": "1EM1",
        "rooms": "630",
        "teachers": "C"
    }
];

// Create an accumulator object and group class objects by examId.
const classDataByExams = data.reduce((acc, x) => {
    // Destructure object with exam key and other keys into class data.
    const { exam, ...classData } = x;
    // Add the examId if not present, then add the classData.
    (acc[x.exam] = acc[x.exam] || []).push(classData);
    return acc;
}, {});

// Convert the object into an array format.
console.log(Object.keys(classDataByExams).map(x => ({ 'exam': x, 'classes': classDataByExams[x] })));

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

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

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

Issue with debugging capabilities in Javascript on VSCode has been detected

UPDATE: I'm seeking guidance on configuring VSCode for debugging Javascript. While I'm familiar with JavaScript functioning in a browser, I find it tedious to rely solely on console.log(). I am looking to debug and step through my code effectivel ...

Using Boolean functions in ngStyle allows for dynamic styling of elements in Angular templates

<div *ngFor= “ let singleorder of order.order”> <p [ngStyle]=" 'color':(singleorder.status === 'CONFIRM' )? 'green' : 'red' , 'background' : (singleorder.status === ' ...

Fancybox's Exciting Tandem Events

I am currently experiencing an issue with my popup ajax contact form as it only has one close event... The AJAX contact form I have consists of two buttons, SEND and CANCEL. When I click the SEND button, the Sweet Alert confirmation message displays ...

What is causing ES6 Class properties to be concealed by Higher Order Functions?

UPDATE: Added new screenshots to provide clarity at the end. My current challenge involves utilizing high order functions to combine subclasses/mixins. I've noticed that I can only access properties from the first class I extend, and only properties ...

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

Accessing Information from the Service

Here's the code snippet for my controller and service: var app = angular.module('myApp', ['ui.bootstrap']); app.service("BrandService", ['$http', function($http){ this.reloadlist = function(){ var list; $http.g ...

What is the reason behind the removal of the "disabled" attribute when setting the "disabled" property to false?

Initially, I have a disabled button: <button disabled="disabled">Lorem ipsum</button> When using button.getAttribute('disabled'), it returns "disabled". But once the button is enabled with JavaScript: button.disabled = false; The ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Error: Unable to locate the specified Typescript function

For the source code, please visit https://github.com/zevrant/screeps I am encountering an issue with my implementation of interfaces in TypeScript. When trying to call the implemented interface, I am getting the following error: "TypeError: spawn.memory.t ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

Angular directive for dynamic template inclusion

I am facing an issue while creating a directive that should automatically add tabs and their content. The problem I'm encountering is retrieving the content stored in partials/tabs/tab[x].html. In my code, I have defined a constant named AvailableTab ...

Transferring data between two "Data" elements using Jquery Datatable

Utilizing the JQuery datatable, I have made the first column of my table clickable, which is labeled as RequestNo. Here's the code snippet: "ajax": { "url": "/Request/Search/LoadData", "type": "POST", "datatype": "j ...

Adding or Deleting Rows from Input Table

I'm in the process of creating a website that features an input table allowing users to easily add or remove rows at their discretion. The desired UI is shown below: https://i.sstatic.net/EFAlM.jpg Here is the HTML code I have developed so far: & ...

Exploring the functions of the elasticsearch javascript library: Understanding the search_type feature

Currently, I am attempting to run a search query using search_type of count with the elasticsearch.angular.js version sourced from the npm module. The query can be successfully executed as follows: POST /index1/type1/_search?search_type=count { " ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...

Difficulties with validating phone numbers

I'm having an issue with my JavaScript code that is supposed to validate a phone number field, but it doesn't seem to be working. Even if I enter incorrect values, the form still submits. Here's the snippet of my code: <script> functi ...

Unexpected syntax error occurs while retrieving data from web API using jQuery AJAX request

I'm attempting to retrieve a json object from the following URL: You may not understand much as it's in Greek, but the format is json. Below is the code snippet I'm using: function getDicts() { api_url = 'https://test3.diavgeia.gov ...