Combine identical items in a JavaScript array based on how often they appear

I have an array in JavaScript that looks like this:

[
  { quantity: 1, name: 'Menu sandwiches' },
  { quantity: 1, name: 'Menu sandwiches' },
  { quantity: 1, name: 'Menu sandwiches' },
  { quantity: 1, name: 'Pizza' },
  { quantity: 1, name: 'Piza' }
]

Now, I want to transform this array into:

[
  { quantity: 3, name: 'Menu Sandwich' },
  { quantity: 2, name: 'Pizza' }
]

Can someone please help me achieve this?

Answer №1

Suppose the values in the initial array are not always 1:

function combineQuantities(arr) {
  let result = {};

  arr.forEach(({quantity, name}) => {
    result[name] = result[name] || {name, quantity: 0};
    result[name].quantity += quantity;
  })

  return Object.values(result);
}

This function creates a new object with attribute names based on the 'name' property of each item in the array. It then loops through the array, accumulating quantities for each unique name. The final output is an array without keys, just the desired form.

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

Dealing with AngularJS memory leaks caused by jQuery

How can I showcase a custom HTML on an AngularJS page using the given service? app.service('automaticFunctions', function ($timeout) { this.init = function initAutomaticFunctions(scope, $elem, attrs) { switch (scope.content.type) { ...

Unable to expand or collapse rows in ng-table

Looking to implement an expand and collapse feature for ng-table, where clicking on a row should expand it to show more detail. However, currently all rows expand on click. Any ideas on how to achieve this? Any assistance would be greatly appreciated, tha ...

When traversing across different child elements, the MouseEvent.offsetX/Y values get reset to 0

Check out this interactive example. The demonstration includes a main div with 3 child divs. A click event is triggered on the main div, but instead of displaying alerts with the mouse position relative to the parent div as expected, it shows the position ...

importance of transferring information in URL encoded form

Recently, I started learning about node.js and API development. During a presentation, I was asked a question that caught me off guard. I had created a REST API (similar to a contact catalog) where data was being sent through Postman using URL encoded PO ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

Leveraging information beyond the socket.on function

I'm trying to work with socket data in a way that allows me to compare it outside of the initial socket.on function. I've attempted using global variables without success. One thought I had was grouping the data, but one is an io.emit and the oth ...

Simplify your code with promises in JavaScript

Running on an API with node v6.3.0, I have the following code that executes two separate promises based on a conditional check for a parameter in a POST request. if (paramExists) { // query database with this condition User.filter(/* utilize param ...

How can I save a pair of characters from two character arrays into an array of integers in C programming?

I am working on a program that involves taking characters from two separate arrays, combining them without addition, and storing the result in an integer array index. The goal is to display the concatenated ASCII value of the two characters when that speci ...

Tips for implementing an onclick jquery function within an input field

Just starting out with JavaScript and jQuery, I have a jQuery function that looks like this: $('.input-group .date').datepicker({ }); I want to apply it to the following HTML structure: <div class="input-group date" id="dp3"> <inp ...

Bootstrap - Keeping track of the collapse state of <div> elements after page refresh

Looking for some guidance as a javascript/jquery beginner - I am utilizing Bootstrap along with data-toggle and collapse classes to display or hide divs. I have been searching online trying to find a solution that will maintain the state of all divs, wheth ...

Sending a json array from PHP

I spent several hours searching for solutions to my problem but couldn't find an answer. I'm trying to perform a search on the same page using jQuery, AJAX, and PHP. Unfortunately, the array from PHP is still returning undefined. Here is the P ...

Retrieve information from a URL using an Express API

Every 45 minutes, my API receives a request: GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama} I need to extract {device}, {data}, {time}, and {customData#trama} from the URL and store them in separate variables. This ...

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

The functionality of Next.JS Cpanel Deployment Server.js appears to be malfunctioning

Trying to deploy my website on cpanel, I am utilizing a node.js application with cpanel. Here is the configuration: https://i.sstatic.net/AXap3.png However, when I start my server, it displays "503 service unavailable." https://i.sstatic.net/17JAu.png ...

What is the best way to break down the elements of an array

I attempted to parse a string array using the given code, but unfortunately, the expected data did not get printed. Can someone please guide me on how to rectify this issue? Thank you. Structure of the $data Array : Array ( [js] => Array ( ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

A guide on utilizing ng-repeat to iterate through array values in Views

Need help with using ng-repeat on array values within an ng-repeat in VIEWS? The second ng-repeat is not functioning properly. Here is the value of generalDocument.documents: ["14-10-2015.xls","15-10-2015.xls","16-10-2015.xls"] <div class="box-body ...

What are the different ways to format a .SQL file in real-time when it is located on an internal website?

In order to upload files to my local server for future reference and training purposes, I am looking for a way to easily format SQL and C# code. I believe there must be a JavaScript library available that can meet these specific needs. My ideal solution ...

How can we access parameters in ag-Grid's Angular 1 onFilterModified event?

Currently, I am incorporating grid options using the code snippet provided below: var gridOptions = { columnDefs: columnDefs, rowData: null, enableFilter: true, onFilterChanged: function() {console.log('onFilterChanged');}, onFilterModified: fun ...

Comparing Strings in the C Programming Language

I am attempting to validate the names entered by users. If a name already exists, I prompt the users to re-enter the name. However, there seems to be an issue with the program when it runs. Your assistance is greatly appreciated! { #define MAX 3 char *Nam ...