Calculate the sum of number values within an array of objects while maintaining the group value

let myArrayOfObjects = [{Group:MD,qtyA:4,qtyB:5},{Group:IL,qtyA:1,qtyB:3},{Group:FL,qtyA:5,qtyB:5}];

//EXPECTED RESULT:
// [{Group:MD,Total:9},{Group:IL,Total:4},{Group:FL,Total:10}]

I am currently utilizing the reduce method to extract data from myArrayOfObjects. However, I am struggling with calculating the total quantity for each Group while still maintaining the Group information in the resulting array of objects.

Answer №1

To achieve this task, you can utilize the Array.map() method along with Array.reduce():

let data = [
  { Category: "Books", price: 20, quantity: 3 },
  { Category: "Electronics", price: 50, quantity: 2 },
  { Category: "Clothing", price: 30, quantity: 1 },
];
let result = data.map(({ Category, ...prices }) => ({
  Category,
  TotalCost: Object.values(prices).reduce((acc, val) => acc + val, 0),
}));
console.log(result);

Answer №2

This method will add together all numerical values within a specified group. You can utilize the map() function to obtain individual results for each group, and then employ reduce() to determine the total quantity.

const myArrayOfObjects = [
  { Group: "MD", qtyA: 4, qtyB: 5 },
  { Group: "IL", qtyA: 1, qtyB: 3 },
  { Group: "FL", qtyA: 5, qtyB: 5 },
];

const result = myArrayOfObjects.map((group) => ({
  Group: group.Group,
  Total: Object.values(group).reduce((total, quantity) =>
    typeof(quantity) === "number" ? (total += quantity) : total, 0
  ),
}));

console.log(result)
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

What is the procedure for accessing the export function of photoeditorsdk in order to retrieve the image URL?

I am facing difficulty retrieving the updated image URL from the PhotoEditor SDK. This issue arises while trying to integrate the PhotoEditor SDK with Angular. let templateStr: string = ` <ngui-react [reactComponent]="reactComponent" [react ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...

"Concurrency issues arise when using multiple AJAX calls in jQuery, causing confusion with

This piece of JavaScript code involves a series of AJAX calls to my FastCGI module in order to retrieve certain values. However, there seems to be an issue where the value intended for display in "div2" is ending up in "div1", and vice versa, ultimately ca ...

Present information using Vue.js

Struggling to display just the name from the request object in my form using JavaScript. I'm new to working with JS and need some guidance. I attempted to use {{ request.name }}, but it's not functioning as expected. When I tried {{request}}, it ...

Obtain user input dynamically rather than statically assigning values in an array

Is there a way to retrieve user input from a form using jQuery and add it to a PHP array for a Wordpress query? Specifically, I want to replace the hardcoded value '123456' in the PHP array with the value stored in a variable generated by my jQue ...

Stop jwplayer video from being downloaded on the Chrome mobile browser

Currently, I am facing an issue with the JWPlayer video where I am unable to prevent it from being downloaded. On mobile Chrome browser, if I double click while the video is playing, it gives me the download option, which is not ideal. Despite going throu ...

I'm currently in the process of building a brand new React.js application by utilizing the command "npx create-react-app". However, upon completion, I encounter an error while attempting to run it with the command "npm start"

Below is the complete error message Error message from ./src/index.js at line 1, character 58 Failed to parse module: Unexpected token found at (1:58) The following loaders were used to process the file: * ./node_modules/@pmmmwh/react-refresh-webpack-pl ...

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...

Update the HTML table by changing the first cell in the first row to span multiple

I currently have a table structured like this: <table> <thead> <tr> <th></th> <th>Col1</th> <th>Col2</th> <th>Col3</th> <th>Col4& ...

Exploring the functionality of the JavaScript Date constructor in relation to

Will using new Date('2015-01-01') provide me with the exact moment equivalent to 2015-01-01T00:00:00Z? ...

What is the process for setting up a banner on one page that will automatically be reflected on all other pages?

Is there a way to have a banner in a div and display it on the home page so that it automatically appears on all other pages without needing to place the code on each page individually? Any assistance would be greatly appreciated :) ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

methods for including a sub-array into a main array within Swift

{ "firstName": "AA", "lastName": "BB, "shortName": "CC", "nric": "12/AAA(N)123456", "gender": "F", "dob": "1.1.2000", "password": "admin123", "photo": { "image": "hello", "thumb": "world" } } Is it possi ...

"Dynamic" visual in a Vue.js development scheme

Utilizing Vue.js for the development of a hybrid mobile application has been my current focus, with the Quasar framework serving as a key component. Recently, I incorporated an image into the application using the <img /> tag and utilized the followi ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

Halt the iteration process and confirm a true result upon discovering a match between two arrays

I have two databases, one stored in indexedDB and the other in PouchDB (even though I am aware that PouchDB is built on top of indexedDB). The dataset in indexedDB contains a list of rooms, which was saved through a previous page and is now being displaye ...

What is the best way to incorporate flags in a nodejs application when using npm run-script?

I have a NodeJS file that I execute using an "npm" command. I've been attempting to display all arguments (including flags). When the file is executed by directly calling the node executable, it functions correctly. However, when I use the npm command ...

How come the overlay only appears the first time the button is clicked in JQUERY? What could be the issue here?

Why is my purple overlay with yellow text showing only once after the button is clicked, even though I have toggled the function? Check out my codepen to test the issue: https://codepen.io/cat999/project/editor/AEeEdg $('.animate-this').cl ...

Leveraging Javascript to identify actual text content, rather than focusing on HTML elements

Having an issue with a WYSIWYG editor (TinyMCE) saving content into the database where values are sometimes saved that contain only tags like: <p><br data-mce-bogus="1"></p> which is not actual content. My application cannot distinguis ...