Combining the values of duplicate properties to create a new object

I have been working on a task to calculate the total values within an array of objects structured like this:

[ 
  { token: 'N97235', conversions: '2', payout: '100' },
  { token: 'N91567', conversions: '2', payout: '100' },
  { token: 'N91567', conversions: '3', payout: '150' },
  { token: 'N97759', conversions: '2', payout: '100' },
  { token: 'N97240', conversions: '1', payout: '50' },
  { token: 'N13925', conversions: '1', payout: '50' },
  { token: 'N53285', conversions: '1', payout: '50' },
  { token: 'N28312', conversions: '1', payout: '100' },
  { token: 'N96475', conversions: '1', payout: '50' },
  { token: 'N97759', conversions: '2', payout: '100' },
  { token: 'N76951', conversions: '1', payout: '100' },
  { token: 'N39108', conversions: '1', payout: '50' },
  { token: 'N39108', conversions: '4', payout: '200' },
  { token: 'N48854', conversions: '2', payout: '100' },
  { token: 'N50179', conversions: '1', payout: '50' },
  { token: 'N18804', conversions: '1', payout: '50' },
  { token: 'N95631', conversions: '2', payout: '100' },
]

My goal is to sum up all the conversions and payouts in order to create a new object structured as follows

{
  N97235: { conversions: 2, payout: 100 },
  N39108: { conversions: 5, payout: 250 },
  N91567: { conversions: 6, payout: 300},
  N96475: { conversions: 1, payout: 50},
  // ...and so forth
}

What I have attempted involves iterating through the array (tokens_array[] in this case) and assigning the object properties to the newly created object (the conversions_sum{}), yet I encounter issues with initializing the values before adding to them.

tokens_array.forEach(function(element) {
    var token_string = element.token.toString();
    if (!conversions_sum.hasOwnProperty(token_string)) {
        conversions_sum[token_string] = { conversions: 0, payout: 0 };
    }
    conversions_sum[token_string].conversions += parseInt(element.conversions);
    conversions_sum[token_string].payout += parseInt(element.payout);
});

The problem lies in not initially setting the values for conversions_sum[token_string].conversions and conversions_sum[token_string].payout, causing additions to be performed on 'undefined'.

Thank you in advance for any assistance.

Answer №1

To generate a hash object of the tokens, you can utilize the Array.prototype.reduce method in JavaScript. Here is an example implementation:

function group(arr) {
  return arr.reduce(function(h, e) {             
    if(h[e.token]) {                             
      h[e.token].conversions += +e.conversions;  
      h[e.token].payout += +e.payout;            
    }                                            
    else {                                       
      h[e.token] = {conversions: +e.conversions, payout: +e.payout};
    }

    return h;
  }, {});
}

var array = [ 
  { token: 'N97235', conversions: '2', payout: '100' },
  { token: 'N91567', conversions: '2', payout: '100' },
  { token: 'N91567', conversions: '3', payout: '150' },
  { token: 'N97759', conversions: '2', payout: '100' },
  { token: 'N97240', conversions: '1', payout: '50' },
  { token: 'N13925', conversions: '1', payout: '50' },
  { token: 'N53285', conversions: '1', payout: '50' },
  { token: 'N28312', conversions: '1', payout: '100' },
  { token: 'N96475', conversions: '1', payout: '50' },
  { token: 'N97759', conversions: '2', payout: '100' },
  { token: 'N76951', conversions: '1', payout: '100' },
  { token: 'N39108', conversions: '1', payout: '50' },
  { token: 'N39108', conversions: '4', payout: '200' },
  { token: 'N48854', conversions: '2', payout: '100' },
  { token: 'N50179', conversions: '1', payout: '50' },
  { token: 'N18804', conversions: '1', payout: '50' },
  { token: 'N95631', conversions: '2', payout: '100' },
];

console.log(group(array));

Answer №2

Okay, so the first step is to properly set them up, right? Make sure not to overwrite your new object every time, but only do it when necessary. Here's how you can achieve that:

 updated_totals[token_string] = updated_totals[token_string] || {
   conversions: 0,
   payout: 0
 };
updated_totals[token_string].conversions += parseInt(element.conversions, 10);
updated_totals[token_string].payout += parseInt(element.payout, 10);

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

Tips for handling an AJAX form submission with various submit buttons and navigating through Laravel routes

I am having trouble getting the form below to submit to the database. The issue arises when trying to use AJAX to submit the forms. The problem seems to occur at this point: $(i).submit(function(event) { Can someone help me figure out what I am doing wr ...

Is it possible for the sum to turn into NaN in Bootstrap Table JavaScript?

I used bootstrap to create a table that links with phpmyadmin. I need to show the total current amount in the table, which should update when using the search function. However, I keep getting NaN as my result. Below is the relevant code: // PART OF CODE ...

Matrix filled with elements either being 1 or 0

I am in the process of developing a program that generates a random maze comprised of '1's and '0's. The maze does not necessarily have to be solvable. The main functionality of my program is to search through this maze and determine if ...

Having trouble with refreshing the div content when using jQuery's $.ajax() function

My goal is to refresh a div that has the id #todos after saving data in the database. I attempted to use .load() within $.ajax() $('.todo--checkbox').change(function () { let value = $(this).data('value'); $.ajax({ url: ...

The sequence of HTML5 DragDrop Enter and Leave events occur consecutively

I am encountering a problem with a simple drag & drop effect where the class name is changed when the drag enters or leaves, resulting in continuous entering and leaving. Take a look at this basic HTML code: <div class="box"> <div cla ...

Facing a NodeJS error about headers being set when I haven't actually set any

My middleware function checks if the user is logged in on every page load, as shown below: app.use(function(req, res, next) { if (req.cookies.hasOwnProperty('rememberToken')) { app.get('db').Users.find({'rememberToken': ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Tips for concealing a div element once the final section is reached

My website has a sticky footer with a clickable arrow that allows users to navigate through the sections. However, I am facing an issue where the arrow does not disappear once the last section is reached. Being new to jQuery and JS, I'm unsure how to ...

The ng-repeat in the inner loop is excluding the initial element of my array and subsequently placing them in the final HTML tag

I am facing a challenge with converting a JSON array into HTML using angular's ng-repeat. The JSON structure I'm working with looks like: data:{ thing_one:[{ id:1, fields:[{ .... }] }, { id:2, fields:[{ .... ...

Incorporate a pseudo class to a unique custom template or directive within an Angular project

I have been developing a custom dropdown menu directive in AngularJS. The issue I'm facing is that the buttons in my template become inactive when interacting with the dropdown menu, unlike a regular HTML select which remains active while the dropdown ...

"Implementing a button in a flask data table: A step-by-step guide

Hello, I am facing an issue with adding a button to a Bootstrap datatable in Flask (Python) using JavaScript. Any tips or solutions would be greatly appreciated. I am trying to achieve something like this: https://i.sstatic.net/NtaB3.png I have attempted ...

The Bootstrap validator triggers the form submission only after the second click

When I click on the submit button, I am attempting to submit a form that has its default action prevented and first checks a condition before proceeding. Below is the code snippet: $('#payment-form').bootstrapValidator({ live: 'dis ...

Incorporating dynamic form elements using Vue.js within a targeted div

Here is the HTML and Vue.js code that I have: <table class="table"> <thead> <tr> <td><strong>Title</strong></td> <td><strong>Description< ...

Passing a PHP variable between PHP files with the help of jQuery

I'm facing a minor issue. I'm trying to pass a PHP variable from one PHP file to another using setInterval. However, I'm unsure of how to include the PHP variable in my jQuery code. Here is the content of first.php: <?php $phpvariable= ...

Saving custom input strings into a designated position within a 2D array using the C language

I am currently learning about 2d arrays in C, and I am attempting to obtain the user's name and store it in a 2d array. A challenge I encountered is that C does not have a String data type and only supports strings with the data type char. While I ha ...

Creating an Android game with the utilization of HTML5 and Javascript involves the adaptation of images to various screen resolutions

Currently, I am working on creating a basic game for android devices by utilizing HTML5, javascript, and cordova for wrapping it up. One of the key features of my game will involve using an image as a background and animating it to create a dynamic visua ...

Display the overlay solely when the dropdown is visible

My code works, but the 'overlay active' class only functions properly when I click on the button. If I click outside of the button, it doesn't work as intended. I want the 'overlay active' class to be displayed only when the dropd ...

The behavior exhibited by node.js express is quite peculiar

I am currently running an Express server. My process involves uploading an Excel File from HTML, which is then parsed by Express to perform calculations. Each row in the Excel file contains information about a User's address. For each address, our ...

The CSS theme toggler for Bootstrap

I am currently working on integrating a style switcher following the instructions provided at . However, when I add a title="" attribute to the CSS link, the CSS file fails to load on the page and the styles revert back to default Bootstrap. I have added ...

The Angular 2 view will remain unchanged until the user interacts with a different input box

I am currently working on implementing form validation using Reactive Forms in Angular 2. Here is the scenario: There are two input fields Here are image examples for step 1 and step 2: https://i.stack.imgur.com/nZlkk.png https://i.stack.imgur.com/jNIFj ...