Combining and adding arrays that share the same key

Currently, I am working with a for loop that extracts data for each user from the matchlistResponsestats object. Once the for loop completes its iterations, I end up with approximately 90 arrays in this format:

["username", kills, assists, deaths]

My goal is to combine and sum up the data from these arrays for each username. Additionally, I want to append a new value at the end of each array indicating the number of arrays merged into that specific username.

for (var i = 0; i < matchArrayTotalPlayer; i++) {
            if(matchlistplayers[i].username === username) {

              const matchlistplayerkills = matchlistResponsestats.players[i].kills
              const matchlistplayerheadshots = matchlistResponsestats.players[i].headshots
              const matchlistplayerdeaths = matchlistResponsestats.players[i].deaths
              const matchlistplayerusername = matchlistResponsestats.players[i].username
              console.log(matchlistResponsestats)
              var playermatchstats = [matchlistplayerusername, matchlistplayerkills, matchlistplayerheadshots, matchlistplayerdeaths]
            }

The resulting output from the for loop (playermatchstats) takes the form:

["dJadebisi", 17, 5, 19], ["softarlugnt", 16, 8, 22], ["pruttstjert", 1, 0, 5], ["dJadebisi", 16, 4, 8], ["pruttstjert", 10, 0, 15], ["softarlugnt", 9, 1, 20]... 

Desired output should resemble this:

["dJadebisi", 33, 9, 27, 2],["softarlugnt", 25, 9, 42, 2], ["pruttstjert", 11, 0, 20, 2]

If anyone could nudge me in the right direction on how to accomplish this task, it would be greatly appreciated.

Answer №1

To accomplish this task, you can utilize the power of the reduce method.

matchArrayTotalPlayer.reduce( (acc, cur) => {
 const name = cur[0]
 let el = acc.find(item => item[0] === name)

 if (!el) {
  el = [name, 0, 0, 0]
  acc.push(el)
 }

 el[1] += cur[1]
 el[2] += cur[2]
 el[3] += cur[3]
 el[4] ++

 return acc
}, [])

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

Rearrange and place items at the dropped location

I am looking to create a drag-and-drop feature for moving items from a list of products to an empty container. Upon completion, I need to save the location and the selected items in a database so that I can recall this layout later. However, I have encoun ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

What could be causing the redirection to my php file in this particular contact form?

I have a contact form on my website that uses AJAX for submission. Everything seems to be working fine, but when the user clicks on the Submit button, they are redirected to the PHP file instead of staying on the page to see success or error messages. I wa ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Differences Between Vuetify Breakpoints and CSS Helper Classes

As I browse through the Vuetify documentation and various code snippets on the web, I often come across examples that mention using either a Vuetify breakpoint or a CSS helper class to make an element responsive to screen size changes. Is there a preferre ...

Populate a list with corresponding values from a HashMap in Java

For an assignment, I am required to use an Array instead of an ArrayList, even though the latter would make the task easier. I have a HashMap filled with different animals based on their colors. The objective is to create a separate Array and populate it w ...

Utilizing Immutable.js within React's Pure Components

Having some difficulty incorporating React PureComponents with Immutable.js. Take a look at this demonstration: https://codepen.io/SandoCalrissian/pen/QaEmeX The demo showcases 2 components being rendered. The first (NoramlPure) is a regular PureComponen ...

Working with the Enter Key in Vue.js

I am faced with a challenge involving a text field and a button setup. By default, the button is set to submit a form when the Enter key is pressed on the keyboard. My goal is to capture each key press while someone is typing in the text field, particularl ...

Adjusting canvas context position after resizing

I've been experimenting with using a canvas as a texture in three.js. Since three.js requires textures to have dimensions that are powers of two, I initially set the canvas width and height to [512, 512]. However, I want the final canvas to have non-p ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

I have a query regarding the process of filtering data, specifically in the context of

When working with express and mongoose, I often encounter complex queries. As a workaround, I typically retrieve objects by their ID like this: const ticketObj = await Ticket.findById(ticketId); I then use JavaScript's filter method to further narro ...

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...

How can I retrieve a data field with a colon in its key using Cytoscape.js?

After diligently going through the official documentation and following the steps in the tutorial, I have successfully managed to access a node's data field and use it for labeling, as long as the key is a simple string. However, my data will contain ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

Adding navigation buttons to a Material-UI Select component: A step-by-step guide

Currently, I have integrated a Select component from MUI and it is functioning well. When an item is selected from the list, the router automatically navigates to that location: This is the snippet of code being used: export default function SelectLocatio ...

AngularJS - ng-repeat: Warning: Repeated items found in the repeater and are not allowed. Repeater:

I'm currently using ng-repeat to showcase a collection of items fetched from the Twitter API. However, I am encountering an issue where Angular attempts to display the empty list while the request is still being processed, resulting in the following e ...

Transforming an unordered list to function similarly to a select input

I am looking to style a ul list to function as a select form element. I have successfully populated a hidden input using my code. Now, I am trying to make the ul behave like a select input when either the keyboard or mouse is used. Previously, I had some ...

Error: The property value supplied for the calc() function is invalid

<App> includes both <Header> and <Content> components. I am attempting to calculate the height of <Content>, which is equal to the height of <App> minus the height of the header. // App.js import { useStyles } from "./Ap ...