Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this:

var data = [
  {
    student: "sam",
    English: 80,
    Std: 8
  },
  {
    student: "sam",
    Maths: 80,
    Std: 8
  },
  {
    student: "john",
    English: 80,
    Std: 8
  },
  {
    student: "john",
    Maths: 80,
    Std: 8
  }
];

My goal is to calculate the total marks for a specific student, regardless of subject (in this case, student 'sam').

To achieve this, I plan to filter the data array by student name and then iterate through the filtered data entries to calculate the total marks for that student.

I am wondering if there is a groupBy function available in TypeScript similar to SQL that could simplify this task.

Answer №1

To achieve this task, one can utilize a simple reduce method on the array. The reduce function will loop through each item in the array and apply the provided predicate function to it. Each iteration should output the accumulator object/array/value.

If you are unsure about the desired data structure, you have the flexibility to control it by manipulating the function passed to reduce.

  studentScores = this.data.reduce((accumulator, item) => {
    const key = Object.keys(item)
      .filter(k => k !== 'student')
      .filter(k => k !== 'Std')[0];
    const prevValue = accumulator[item.student] || 0;
    const studentName = item.student;
    accumulator[studentName] = prevValue + item[key];
    return accumulator;
  }, {});

You can find a functional example on StackBlitz at https://stackblitz.com/edit/angular-xcjzzf

Answer №2

To organize the data, utilize a dictionary. You can easily group items by creating a map, but since the names are changing, the task becomes challenging. Check out this link to view the code in action: stackblitz.

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

Highchart encountering issues with multiple Y axes

My highchart is causing Chrome to crash when I add the second series. I am unable to see the Chrome console for debugging purposes.. :( Does anyone have any suggestions? $(function () { var chart; $(document).ready(function() { chart ...

When the window is scrolled to 50%, I would like to load some additional data

Looking to load data when the browser scrollbar reaches 50%... In jQuery, I created the following function: $(window).on('scroll', function () { alert("scrolling"); if ($(window).scrollTop() + $(window).innerHeight() > ...

Are you looking for a way to prevent the default behavior of an event in angular-ui-router 1.0.x? Check out

Recently, I made a change in my code where I replaced $stateChangeStart with $transitions.onStart $rootScope.$on('$stateChangeStart', function(e, ...){ e.preventDefault(); // other code goes here... }); Now, the updated code looks lik ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...

My code cannot send a POST request successfully, even though it works fine in Postman

reg.ts var data = JSON.stringify({ "name": { "value": this.registerForm.value.email }, "mail": { "value": this.registerForm.value.email }, "pass": { "value": this.registerForm.value.password }, "field_user_type": { "value": & ...

What is the process for changing the border color of a material selection?

Is it possible to customize the border color of a material select element? I attempted changing the border color using css from: to this: Any suggestions on how to achieve this? Appreciate any assistance you can provide! ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

React/React Hooks: Want to initiate input validation when a user deselects a checkbox

Currently, my component includes an input field and a checkbox. When the checkbox is checked, it disables the input field and clears any validation errors. However, I want to add functionality so that if the checkbox is unchecked, the input field becomes ...

What is the best way to confirm checkbox selection based on MySQL data?

Writing this question feels challenging, but I have a collection of checkboxes with their data stored as JSON in my PHP database. What I'm trying to achieve now is to dynamically load the JSON data on the page without refreshing it, checking specific ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...

How do I combine Firefox binary specification with adding the Firebug extension when using Selenium?

Presently I am utilizing the code below. var co = require('co'); var WebDriver = require('selenium-webdriver'); var SeleniumServer = require('selenium-webdriver/remote').SeleniumServer; co(function *() { // async var ser ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

What are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

What is the best way to utilize unique slash commands in Slack threads?

After setting up a custom slash command /news in Slack, it appears to work fine. However, I'm struggling to figure out how to trigger slash commands within threads. Whenever I try to use the command, I receive this error message: /news is not support ...

Unexpected TypeError when using Response.send()

Here is a snippet of my simple express code: const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) In my development environmen ...

Choosing multiple values in the selectize plugin from the controller: A step-by-step guide

Need help with selecting multiple options I'm utilizing the following plugin: https://github.com/selectize/selectize.js/blob/master/docs/usage.md I have an object as displayed in the image below: https://i.stack.imgur.com/sQsKe.png This is my Client ...

Integrate the elements from the <template> section into the designated <slot> area

I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span elements inside the template using the ::slotted selector. However, it seems like this functionality is not working as I expected. <!doctype h ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...