Add up the quantity when all remaining elements in the dictionary are identical

Below is an array of dictionaries:

[{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

I'm looking to sum up the counts for each name and create a new dictionary like this:

[{name:'v1', count:2}, {name:'v2', count:2}]

Answer №1

Utilizing Array.prototype.reduce, Object.entries, and Array.protype.map for the solution:

const data = [{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

const result = Object.entries(data.reduce(
  (acc, { name, count }) => {
    acc[name] = count + (acc[name] || 0)
    return acc
  },
  {}
)).map(([name, count]) => ({ name, count }))

console.log(result)

Breaking down the solution into separate parts for better comprehension:

const data = [{name:'v1', count:1}, {name:'v1', count:1}, {name:'v2', count:1}, {name:'v2', count:1}]

const r1 = data.reduce(
  (acc, { name, count }) => {
    acc[name] = count + (acc[name] || 0)
    return acc
  },
  {}
)
console.log(r1)

const r2 = Object.entries(r1)
console.log(r2)

const r3 = r2.map(([name, count]) => ({ name, count }))
console.log(r3)

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

unable to use 'await' keyword to delay the code execution until a function finishes

I'm encountering an issue where I need to wait for the result of a local function before proceeding further. Here is the code for the local function: var Messagehome = (req, res) => { user.find().exec(async (err, user) => { if (err) ret ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

The "maxfilesexceeded" event in dropzone.js does not seem to be triggered when adding files programmatically

In my Vue.js project, I am using dropzone with the maxFiles: 1 option set. To display an existing file from the server in dropzone, I have added the following code: let mockFile = { name: 'Filename', size: file.size }; myDropzone.emit('added ...

Implementation issue with Hashids library in Vue.js causing functionality hiccups

I'm having trouble getting the library hashids to cooperate with vue.js The method I would like to use is: <template> <div class="container"> {{ hashids.encode('1') }} </div> </template> <script& ...

unable to display the responseJson findings

I'm having trouble understanding why this function for an API on National Parks isn't working as expected. As a relatively new programmer, I find that seeking help from others can often shed light on issues I may have missed. Any assistance woul ...

Tips for adding content to several elements at once using jQuery

My HTML structure is as follows : <span class="section2 section4">hello</span> <span class="section1">World</span> <div class="tab" id="tab1"></div> <div class="tab" id="tab2"></div> <div class="tab" id= ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Scanning the header of panel groups for information

I'm currently working on developing a custom search engine to navigate through the panel-group that I've created, but I seem to be struggling with selecting the correct elements. The structure of my generated Markup is as follows: <div id="o ...

bespoke validation using AngularJS

Consider a scenario where there is a table comprising of 10 rows and each row contains 10 columns of checkboxes. Prior to the user submitting the form, it is necessary to implement a validation rule: at least two checkboxes must be checked in each row! & ...

Load a page from a different domain using uframe

Looking for a solution to successfully load an external URI using uFrame. Currently encountering an "Access Denied" issue when attempting to do so on Firefox. Any suggestions? ...

"Resizing a Javascript file resulting in the creation of a faulty base64

I have been attempting to resize images on the client side using HTML5 before uploading. However, it seems that the base64 string is broken as it contains spaces, line breaks, and other unexpected characters. Even after removing them, the string remains br ...

JQuery transmits null values

I have been troubleshooting my code for what feels like forever, but I just can't seem to find the error... My current project involves experimenting with JQuery and AJAX. I created a simple form with a textarea for submission. The form works perfect ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Different Ways to Modify the Appearance of Angular's mat-slide-toggle and mat-checkbox

I am facing an issue in my Angular form where I have a select box containing objects derived from database records. The goal is to automatically populate the form with the object values once one is selected. My Angular application includes an array of obj ...

The Reason Behind Component Non-ReRendering in Redux

I am currently facing an issue with my component and reducer. The `componentDidMount()` method in my component is calling a server to get some data, but the component doesn't re-render after the action is performed. I have checked my code multiple tim ...

Tips for overlooking TypeScript errors during compilation in Webpack's production mode

development environment webpack version 4.41.2 typescript version 3.7.2 issue Compiling files in webpack development mode works fine, but compiling in production mode results in numerous errors that prevent a successful compilation. goal Discover a s ...

Exploring Ways to Modify a .txt File with Javascript or jQuery Forms

Looking for a way to access a .txt file offline in the browser and display its data in different form fields for each line. Any tutorials available for this? ...

Adjusting the orientation of an image using CSS3 depending on the position of the mouse

So I discovered that it's possible to make an image pan left or right using CSS3. Here's an example: HTML <html> <div> <img src="pic.png" class="pan"> </div </html> CSS .pan:hover { margin-right: -50px; } That& ...

SyntaxError: Encountered an unexpected token that is not jsonp, could it be trying to parse json instead?

As a newcomer to AJAX and Javascript, I am attempting to integrate them with an API following this structure: http://localhost:8088/JobPositionForDd: { "data": [{ "_id": "529dc2dfd0bf07a41b000048", "name": "Junior Android" }, { ...

Potential `undefined` Object Error Encountered with Optional Chaining in TypeScript

Currently, I have a response that I am retrieving from: data?.currentOrganization?.onboardingSteps?. It is possible for data, currentOrganization, and onboardingSteps to be null. My goal is to create a variable like this: const hasSteps = data?.currentOrg ...