Combining numerical values with similar string values in a multi-dimensional array to calculate the sum

I'm currently creating a JavaScript cash register application that calculates the exact change based on the available funds in the register. This project is part of a challenge on freeCodeCamp: https://www.freecodecamp.org/challenges/exact-change

Although I've made progress, I've hit a roadblock.

The key function in my program is addResult(), which accepts two parameters: name and val.

var result = [];
function addResult(name, val){
    result.push([name, val]);
}

For instance, if an $18 change is required, the function constructs an array like this:

[["ONE", 1.00], ["ONE", 1.00], ["ONE", 1.00], ["FIVE", 5.00], ["TEN", 10.00]]

However, I want the resulting array to look like this instead:

[["ONE", 3.00], ["FIVE", 5.00], ["TEN", 10.00]]

My goal is to have unique string names but aggregate the numbers together, yet I can't seem to figure out how to achieve this.

If anyone is willing to examine the complete code, here it is:

...

Answer №1

A simple solution might involve modifying the addResult function to first check if the specified name already exists in the list of results, and if it does, then add the provided value to it.

function addResult(name, val){
    let entry = result.find(e => e[0] === name);
    if (entry) {
        entry[1] += val;
    } else {
        result.push([name, val]);
    }
}

let result = [
  ["ONE", 1.00],
  ["FIVE", 5.00],
  ["TEN", 10.00]
];

function addResult(name, val) {
  let entry = result.find(e => e[0] === name);
  if (entry) {
    entry[1] += val;
  } else {
    result.push([name, val]);
  }
}

addResult("ONE", 1);
console.log(result);

Answer №2

Another method to calculate total cash:

function CalculateCash(current,add) {
var holder = {};
current.forEach(function (d) {
    if(holder.hasOwnProperty(d.name)) {
       holder[d.name] = holder[d.name] + d.value;
    } else {       
       holder[d.name] = d.value;
    }
});
add.forEach(function (d) {
    if(holder.hasOwnProperty(d.name)) {
       holder[d.name] = holder[d.name] + d.value;
    } else {       
       holder[d.name] = d.value;
    }
});
var obj2 = [];
for(var prop in holder) {
    obj2.push({name: prop, value: holder[prop]});   
}
    console.log(obj2);
    return obj2;
}

    var current = [
        {name: 'PENNY',       value: 1},
        {name: 'NICKEL',      value: 5},
        {name: 'DIME',        value: 10},
        {name: 'QUARTER',     value: 25},
        {name: 'ONE',         value: 100},
        {name: 'FIVE',        value: 500},
        {name: 'TEN',         value: 1000},
        {name: 'TWENTY',      value: 2000},
        {name: 'ONE HUNDRED', value: 10000}
    ];
    
    var add = [
        {name: 'PENNY',       value: 1},
        {name: 'NICKEL',      value: 5},
        {name: 'DIME',        value: 10},
    ];

CalculateCash(current,add);

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 to Use an Array to Filter Another Array in AngularJS

After attempting to filter a group of checkboxes using an array, the outcome was not what I expected: <ion-checkbox ng-repeat="user in users | filter: {id: group.members}" ng-model="user.checked">{{user.info.name}}</ion-checkbox> The specific ...

Different method for navigating in JavaScript

Currently, I'm in the process of developing a control panel using js and npm. I've run into an issue where I need to reset midway through the code without starting anew. Essentially, what I want is for the system to return to the menu after execu ...

Updating a data with a JavaScript browser script

Recently, I have been attempting to modify the timer in a game using scripts found on various websites. My coding skills are not top-notch, so I am seeking some assistance. I am keeping my fingers crossed that the timer is not server-sided. Upon inspecting ...

Incorporate an additional column into a table using AngularJS

I attempted to insert a new column upon clicking a button, but unfortunately, I was unsuccessful. I have created a JSFiddle demo to illustrate my issue. Any assistance in resolving this problem would be greatly appreciated. Below is my attempt: $scope.a ...

Exploring ES6 Property Assignment

After researching, I've discovered that ES6 does not support setting properties of a class and returning that class. class MyClass { constructor() { this.x = 0; this.y = 0; } update(value) { // logic this.y ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...

Waiting for an API call to complete before loading a specific path in REACT - how can this be achieved?

When using the axios post to request access to the application from the backend, the issue arises when axios returns undefined and then true or false. This leads to a problem in managing the private Route based on these responses. The question is, is axi ...

Error: myFunction has not been declared

Can anyone figure out what's going on here? http://jsfiddle.net/sVT54/ <button onclick="myFunction()">Click me</button> <p id="demo"></p> function myFunction() { document.getElementById("demo").innerHTML="Hello World"; } ...

Discovering the amount of time a section of a webpage remains in view on a browser

I am looking for a way to track user engagement on my website that contains pages with extensive scrolling and numerous images. Each user who logs in sees a unique selection of images. My goal is to monitor how long users linger on each part of the page t ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

Organizing arrays of doubles in increasing sequence

I am currently attempting to manually sort a Double Array in ascending order. The issue I am facing is that the output only displays the smallest value at the top (which is correct), but the other values are shown as 0.0. The range of values is between - ...

Which method of loading website images is quicker: sequential or parallel, utilizing Javascript?

As I work on developing an AJAX image gallery that preloads multiple large images ranging from 120kB to 2MB before the lightbox appears, a question arises: should these images be loaded sequentially (waiting for one to preload at a time) or in parallel? Wh ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

Apple Automation: Extract a targeted string from text and transfer it to a different spot within the page

Apologies for my lack of expertise in this area, but I hope to convey my question clearly. I am working on a form where I need to input text in order to copy specific items and paste them elsewhere on the same webpage. For example, if the input text is " ...

Is there a way to automatically close the Foundation topbar menu when a link is selected?

On my single page website, I am utilizing Zurb Foundation's fixed topbar which includes anchor links to different sections of the page. My goal is to have the mobile menu close automatically whenever a link inside it is clicked. As it stands now, whe ...

The div block containing the table is experiencing horizontal overlap as additional elements are inserted

When creating a table within the div section of the code, I am incorporating text using the DRAG and DROP feature with appropriate styling. The table adjusts in size when I resize my window, indicating that it is functioning correctly. However, as the num ...

Analyzing the Accuracy of Data Between Ground Truth and Predicted Values Stored in N

I need to evaluate the accuracy of my prediction by comparing two numpy arrays. Both arrays are in a 32-bit float format and contain 2-dimensional data. The challenge arises when I attempt to calculate scores by dividing the predicted values by the ground ...