"Calculating the total value of an array based on its individual elements

My API response includes committers to a git project, but some members are repeated because they share the same name with different email addresses.

Example response:

[
  {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7544351417165b161a">[email protected]</a>"},
  {"id": "223411","name": "frank", "commits":4, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8a9e8d8287ac9b84898899a899ec28f83">[email protected]</a>"},
  {"id": "223411","name": "bob", "commits":19, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f4f9f4d6f7f9fb8f5">[email protected]</a>"},
]

In order to get a result like this:

[
  {"name": "bob", "commits":29},
  {"name": "frank", "commits":4},
]

I feel like using both a reduce and a loop could work, but maybe there's a simpler approach that others can suggest. It seems like a common issue that should have an everyday solution!

I tried exploring underscore.js' groupBy function, but it seemed too complex for a one-time use and I couldn't get it to work either :)

Answer №1

Avoiding the need for an extra for loop, you can simplify this task by using the Array.reduce function. Importing a library like underscore to achieve something that native JavaScript can already do might not be the most efficient approach. It could mean importing unnecessary lines of code just to perform a simple task. It's always advisable to refrain from using a library unless absolutely necessary or if it offers multiple functionalities that will be utilized throughout your project.

Here is an example:

const data = [
  {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87b6c7e6e5e4a9e4e8ea">[email protected]</a>"},
  {"id": "223411","name": "frank", "commits":4, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650317040b0e25120d0411001300174b060a08">[email protected]</a>"},
  {"id": "223411","name": "bob", "commits":19, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f6fbf6d4f5fbf8baf7fbf9">[email protected]</a>"},
];

const results = data.reduce( (acc, curr) => {
  acc[curr.name] = acc[curr.name] ? acc[curr.name] + curr.commits : curr.commits;
  return acc;  
}, {});
console.log(results);

Answer №2

Utilize Objects in a similar way to a map by implementing the following:

const array = [
  {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a3b4a6b686924696567">[email protected]</a>"},
  {"id": "223411","name": "frank", "commits":4, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294f5b484742695e41485d4c5f4c5b074a4644">[email protected]</a>"},
  {"id": "223411","name": "bob", "commits":19, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfff2ffddfcf2f1b3fef2f0">[email protected]</a>"},
]; // the response
const map = {};

for (const item of array) {
    const newCommits = item.commits;
    const oldCommits = 
        (typeof map[item.name] === 'undefined') ? 0 : map[item.name];
    map[item.name] = newCommits + oldCommits;
}

const result = [];

// Loop through all keys
for (const key in map) {
    result.push({name: key, commits: map[key]});
}

console.log(result);

Answer №3

To efficiently collect values, consider using a hash table and mapping new objects from the entries.

var data = [{ id: "122334", "name": "bob", commits: 10, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87b6c7e6e5e4a9e4e8ea">[email protected]</a>" }, { id: "223411","name": "frank", commits: 4, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2825280a2b252664292527">[email protected]</a>" }, { id: "223411","name": "bob", commits: 19, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a4a9a486a7a9aae8a5a9ab">[email protected]</a>" }],
    result = Object
        .entries(data.reduce((r, { name, commits }) => {
            r[name] = (r[name] || 0) + commits;
            return r;
        }, {}))
        .map(([name, commits]) => ({ name, commits }));

console.log(result);

Answer №4

If you're looking to group elements, the reduce function is your best friend. To extract the grouped values, utilize the Object.values function.

let arr = [  {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fbecfeeedeca1ece0e2">[email protected]</a>"},  {"id": "223411","name": "frank", "commits":4, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305642515e5b7047585144554655421e535f5d">[email protected]</a>"},  {"id": "223411","name": "bob", "commits":19, "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba9a4a98baaa4a7e5a8a4a6">[email protected]</a>"}],
    result = Object.values(arr.reduce((a, {name, commits}) => {
      (a[name] || (a[name] = {name, commits: 0})).commits += commits;
      return a;
    }, {}));

console.log(result);

Answer №5

Here is a solution that utilizes the JavaScript map data structure.

const repositoryMap = new Map();
repositories.forEach(repo => {
  if (repositoryMap.has(repo.name)) {
    const entry = repositoryMap.get(repo.name);
    entry.numberOfCommits += repo.commits;
    repositoryMap.set(repo.name, entry);
  } else {
    repositoryMap.set(repo.name, repo);
  }
});
console.log(Array.from(repositoryMap.values()));

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

Finding your way to a particular section within a webpage through an external source

Hey there! I'm currently working on creating a link that will direct users to a specific section within my webpage. For example, redirecting them to https://blabla.github.io/my-website. My code is quite straightforward and it functions properly when ...

Using Content-Disposition in ng-file-upload with AngularJS

Context: I am currently working with ng-file-upload to submit two files separately using ngf-selects along with a Javascript object literal. The problem I'm facing is that when the request is sent, all the parts have their content-disposition set to ...

Error: The variable "user" has not been declared in server.js when using passportjs

As a novice with limited experience and a tendency to borrow code snippets from various sources, I'm struggling to identify the root cause of the Reference Error: User is not defined. This particular error crops up when I try to input or submit a new ...

Guide on sending files through an API request with formData() using Vuejs and Axios

My goal is to utilize an API to upload a file to the server. The documentation on documenter.getpostman outlines how to use the API: --form 'type="1"' \ --form 'user_id="1"' \ --form 'file=@"/C:/U ...

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

How can I access a method from another JavaScript file (service) in React JS's App.js to make API requests?

Just starting out with React js and trying to utilize REST API data. I've created a separate file named /shared/job-service.js for this purpose. My goal is to call a method from job-service.js in App.js and display the results on the UI. However, I&ap ...

Discovering a particular element within a Python list by searching for a specific word within the element for printing

I have a list with strings that include both names and locations. I want to print out only the strings in the list that contain either a specific name or location. Although I can use the index to print a specific string and check if a string contains a ce ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

The index array function of PHP's explode algorithm

When using PHP's explode function with the code below $data="test_1, test_2, test_3"; $temp= explode(",",$data); The resulting array looks like this array('0'=>'test_1', '1'=>'test_2', 2='test_3&ap ...

Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application. var app = angular.module('app', []); app.contr ...

Error: The meteor package encountered a SyntaxError due to an unexpected reserved word 'export'

I've made some modifications to a meteor package by adding this line: export const myName = 'my-package' However, I'm encountering an error: export const myName = 'my-package' ^^^^^^ SyntaxError: Unexpected reserved word I ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...