Mapping an array based on its individual values

How can I sum values in an array of objects based on a specific condition?

[{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}]

Is there a method to map and calculate the sums separately for 'a' and 'b' prefixes, resulting in totals of 170 for 'a' and 150 for 'b'?

Answer №1

def combine_amounts(list):
  result = {}
  for item in list:
    if item['prefix'] in result:
      result[item['prefix']] += item['amount']
    else:
      result[item['prefix']] = item['amount']
  
  return result

print(combine_amounts([{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}]))

Answer №2

function calculate_prefix_sums(acc, current) {
    if (acc[current['prefix']]) {
        acc[current['prefix']] += current['amount']
    } else {
       acc[current['prefix']] = current['amount']
   }
   return acc;
}
const array = [{amount:100, prefix:'c'}, {amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}];
const result = array.reduce(calculate_prefix_sums, {});
console.log(result);

My solution is similar to Ali's, but it can compute the sums for any given prefix, not just restricted to 'a' and 'b'.

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

Overloading TypeScript functions with Observable<T | T[]>

Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]> and using T and T[] instead? Here's a basic example to illustrate: import { Observable } from ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Commit to choosing an option from a dropdown menu using TypeScript

I just started learning about typescript and I have been trying to create a promise that will select options from a drop down based on text input. However, my current approach doesn't seem to be working as expected: case 'SelectFromList': ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

Anticipate that the typescript tsc will generate an error, yet no error was encountered

While working in the IDE to edit the TypeScript code, an issue was noticed in checkApp.ts with the following warning: Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams. Surprisingly, when running tsc, no error ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

Is this Firebase regulation accurate and suitable for PUT and GET requests in an Angular and Firebase environment?

Creating a system where users can only see their own posts and no one else can access them is my main goal. Authentication along with posting functionality is already in place and working, but I want to implement this without using Firebase restrictions. ...

Exploring TypeScript integration with Google Adsense featuring a personalized user interface

After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did: In the index.html file: <!-- Global site tag (gtag.js) - Google Analytics --> <script> (function(i,s,o,g,r,a,m ...

Removing a value from a hashmap using Typescript - what is the best way to do it?

After successfully implementing a hashmap in typescript following a helpful post, I am facing an issue with removing something from the hashmap. TypeScript hashmap/dictionary interface To add a key to the keys field of my abstract Input class's hash ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

Generate detailed documentation for the functional tests conducted by Intern 4 with automated tools

I need to automatically generate documentation for my Intern 4 functional tests. I attempted using typedoc, which worked well when parsing my object page functions. However, it failed when working with functional test suites like the one below: /** * Thi ...

What is the proper way to utilize a service within a parent component?

I need assistance with setting up inheritance between Child and Parent components. I am looking to utilize a service in the Parent component, but I have encountered an issue. When attempting to input the service in the Parent constructor like this: expor ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...