Adding up elements in a vector using TypeScript

Is there a way to calculate the sum of values based on the name without repetition in "dataGrf"? I've tried various methods but am facing difficulties. Here is a brief example below to help illustrate what I'm attempting to achieve.

Note: Please excuse any errors in my English

Example) data: = [
  { 'id': 1, 'value': 10, 'name': 'Mary' },
  { 'id': 2, 'value': 5, 'name': 'John' },
  { 'id': 3, 'value': 2, 'name': 'Mary' },
  { 'id': 4, 'value': 3, 'name': 'Lauren' },
  { 'id': 5, 'value': 2, 'name': 'Lauren' },
  { 'id': 6, 'value': 6, 'name': 'Mary' },
];
expected result: 

dataGrf: [
  { 'name': 'Mary', 'valueAcum': 18 },
  { 'name': 'John', 'valueAcum': 5 },
  { 'name': 'Lauren', 'valueAcum': 5 }
]

My ChartModel:

export class ChartModel {
  constructor(
      public name?: string,
      public valueAcum?: number
  ) { }
}

Function used for calculation:

loadData() {
    this.loading = true;
    this.dataChart.emit(null);

    this.dataService.getData(this.year, this.month).
      subscribe((data: dataModel[]) => {

        let dataSort: dataModel[];

        dataSort = data.filter(f => f.value> 0)
        dataSort = dataSort.sort((a, b) => a.value> b.value? -1 : 1)

        this.dataChart.emit(dataSort);

        this.dataGrf = new Array<ChartModel>();

        let valueAcum= dataSort.reduce((sum, record) => {

          let nameArea = data.map(f => f.name);
          nameArea = nameArea.filter(function (item, pos) {
            return nameArea.indexOf(item) == pos;
          });

          if (record.name === nameArea[0]) {
            return sum + record.value;
          }
            return sum;
        }, 0);

        dataSort.forEach(f => {
          this.dataGrf.push(new ChartModel(f.name, valueAcum))
        });

        this.loading = false;
      }
  }

Answer №1

To perform data transformation, you can utilize the reduce function to generate a new object with keys representing names and values containing objects with name and valueAccum keys. Subsequently, convert this object into an array using Object.values:

const users = [
  { 'id': 1, 'value': 10, 'name': 'Mary' },
  { 'id': 2, 'value': 5, 'name': 'John' },
  { 'id': 3, 'value': 2, 'name': 'Mary' },
  { 'id': 4, 'value': 3, 'name': 'Lauren' },
  { 'id': 5, 'value': 2, 'name': 'Lauren' },
  { 'id': 6, 'value': 6, 'name': 'Mary' },
];

const result = Object.values(users.reduce((accum, { name, value }) => {
  const accumValue = accum[name] ? accum[name].valueAccum : 0;
  accum[name] = { name, valueAccum: value + accumValue };
  return accum;
}, {}));

console.log(result)

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

Monitoring changes in the Firebase database using TypeScript

Currently, I am accessing my firebase realtime database through an angular service with the following code: readItems() { return this.af.database.ref(`/path`) .on('value', snap => this.callback(snap.val())); } The callback functi ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

Is it possible to minimize the number of accessors needed for reactive forms?

Currently, I am dealing with a reactive form that consists of 20 different inputs. An example of one input is shown below: <input formControlName="name" matInput> For each input, I find myself needing to write an accessor function like the ...

Error Alert: Redundant Identifier in Angular 2 TypeScript Documents

After following the Angular2 TS Quickstart guide, I noticed duplicate files scattered across various folders in my project. For browser: typings/browser node_modules/angular2/typings/browser Regarding es6-shim: node_modules/angular2/typings/es6-shi ...

The `setState` function is failing to change the current value

I'm having an issue with setting State in the dropdown component of semantic-ui-react while using TypeScript in my code. The selected category value is always returning an empty string "". Any suggestions on how to resolve this problem? impo ...

What causes an undefined error to occur when setting default values after destructuring and assigning props in JavaScript?

Encountering issues with TypeScript in React that have arisen after updating Typescript, ESLint, Prettier, React, and Webstorm to their latest versions. Interestingly, no errors occur when the code is run on the web despite these updates. An example of a ...

Angular File Upload Button Tutorial

English is not my first language, so please excuse any mistakes. I recently started learning Angular and I'm attempting to build a file upload button that lets users upload files based on dropdown menu options (such as USA States). Once uploaded, the ...

Intellisense not working with express

After using the command npm install --save @types/express to install, I imported in my ts file as follows: import * as express from "express"; var app = express(); Despite this setup, I am not able to get intelisense on the app variable. Additionally ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

Are there any notable purposes for using the `.d.ts` file extension beyond just improving code readability?

Within my project, I have a file named shims-vue.d.ts located in the src folder: declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } I ...

Tips for effectively matching a type definition pattern in TypeScript

Good evening! I'm currently working with Angular and rxjs, but I have a feeling that TypeScript is going to play a significant role in my project today. I've been exploring different methods to achieve my goal, but it's definitely challengi ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Issue encountered with the props type upon import, Ts(2322)

Seeking assistance with a TypeScript, StyledComponent, and React project using Create React App. Encountering an error during build time that cannot be ignored. // browser and terminal error TypeScript error in ./src/index.tsx(4,1): Type '{ alt: ...

Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased. Now, I'm curious about how to utilize the created/mounted lifecycl ...

Injecting services with an abstract class is a common practice in Angular library modules

In my development workflow, I have established an Angular Component Library that I deploy using NPM (via Nexus) to various similar projects. This library includes a PageComponent, which contains a FooterComponent and a NavbarComponent. Within the NavbarCom ...

"Dividing" a task stream/executer

Consider the following action type: interface SaveFoo { type: 'SAVE_FOO' payload: { id: string value: number } } I have a requirement to implement a saga that will apply throttling selectively. For instance, if the following actio ...

Adding an active class on a selected chat list item in Angular - here's how!

We are currently developing a chat component where users can click on the left side chat item to open messages with the selected user. We have implemented an active class that changes the color of the selected chat list item. Our goal is to apply the activ ...

The issue arises when interfaces are extended by another interface

Is there a way to have classes that implement both the Observer and Comparable interfaces together? interface Comparable<T> { equals: (item: T) => boolean; } interface Observer extends Comparable<Observer> { notify: () => void } ...