Instructions on merging elements in an array with identical property values

Consider the array below:

[{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}]

Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows:

[{a:1,b:1},{a:(5+10),b:2},{a:20,b:3}]

Answer №1

An efficient way to achieve this is by utilizing a combination of Array.reduce and Array.find. Take a look at the code snippet below:

const mergedResults = dataToMerge.reduce((merged, current) => {
  const existingItem = merged.find(item => item.id === current.id);

  if (existingItem) {
    existingItem.value += current.value;
  } else {
    merged.push(current);
  }

  return merged;
}, []);

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

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

exploring an array using boolean conditions

Seeking assistance as a beginner with creating a boolean search function in my AccountCollection class. The goal is to print a single account based on the account number provided, using a method from the Account class. If the account number is invalid, it ...

Can you explain the distinction between using <router-view/> and <router-view></router-view>?

In various projects, I have encountered both of these. Are they just "syntactic sugar" or do they hold unique distinctions? ...

Display a modal pop-up containing HTML content

I recently started building a small website using Zurb Foundation. I have created a basic grid layout with large metro style div thumbnails (about 10 on the page). Now, I want to enhance user interaction by implementing modal windows that appear when a th ...

"Vue js: Embracing Labeling and Agile Transformation in Dynamic

Is it possible to dynamically change the input field's type and label between text, email, and number in Vue.js? I am new to this framework and would like to learn how to do this. <input type="email"> ...

Is Ember CLI experiencing issues due to the latest Ember Data update?

Greetings! I am a beginner with Ember and recently encountered some warnings after upgrading to the latest version of Ember Data: Update: I have two identical versions of my app, one built without ember-cli and the other with ember cli. Both applications ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Troubleshooting NodeJS CORS issue in Vue project as localhost API calls fail

Having an ongoing project that utilizes a NodeJS/Express backend and a VueJS frontend, I am consistently encountering CORS errors: Cross-Origin Request Blocked: The Same Origin Policy restricts access to the external resource at https://localhost:8080/api ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

The Javascript countdown feature may experience issues on Safari and IE browsers

Why does this function work in Chrome, but not on IE or Safari? function countdown(){ var dDay = new Date().getUTCDate() + 1; var dMonth = new Date().getUTCMonth() + 1; var dYear = new Date().getUTCFullYear(); var BigDay = new Date(dYear+ ...

Mongoose reminds us that static is not a method

I encountered an error message stating that "product.try() is not a function." Interestingly, when I immediately invoke the try() function, it works fine and node recognizes the model "product." I'm starting to wonder if there's something funda ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

What is the process for separating static methods into their own file and properly exporting them using ES6?

After exploring how to split up class files when instance and static methods become too large, a question was raised on Stack Overflow. The focus shifted to finding solutions for static factory functions as well. The original inquiry provided a workaround ...

Learn how to find and filter elements in arrays that do not include a particular value using React

In my collection of recipes, I have the ability to filter out the ones that include specific ingredients. However, when I attempt to reverse this process by using .some method, it only checks the first item in the array. Here is an example of my data stru ...

Utilizing Google Maps API version 3 to display various groups of markers

I am encountering an issue while trying to plot fixed markers and a user position marker on a Google Map. I want to use different images for these markers, but something strange is happening. When the page loads, all fixed markers show up correctly initial ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...