Function in AngularJS to increment counts based on matching names

Check out my angular application on this Plunker link

The text area in my app contains data in the format of (key, count). My goal is to sum up these values using the calc() function.

When the user clicks the button, I want the total summation to be displayed. I have managed to separate the data into different arrays but need help with adding values when the keys match.

EDIT: Please take note of the recent updates in my Plunker project.

I'm new to both Angular and JavaScript, so any assistance would be appreciated!

Answer №1

This code snippet should get the job done.

JS:-

$scope.calc = function() {
  $scope.users = {};

   $scope.values.split('\n').forEach(function(itm){
     var person = itm.split(','),
         name,
         key;

      if(! itm.trim() || !person.length) return;

      name = person[0].trim()
      key = name.toLowerCase();

      $scope.users[key] = $scope.users[key] || {name:name, count:0};
      $scope.users[key].count += +person[1] || 0;
    });
}

HTML:-

<div class="alert alert-success" role="alert">
 <ul>
  <li ng-repeat="(k,user) in users">The total for {{user.name}} is {{user.count}}</li>
 </ul>
</div>

Check out the demo here

Add a shim for the trim() method to support older browsers.

Answer №2

Here is an alternative method to achieve the same result. I cannot comment on the performance comparison with PSL's method, but in my opinion, this code is easier to understand for someone not very proficient in javascript.

function groupByName(names) {
  inputArray = names.split('\n');
  outputArray = {};

  for (i = 0; i < inputArray.length; i++) {

      var keyValuePair = inputArray[i].split(',');
      var key = keyValuePair[0];
      var count = Number(keyValuePair[1]);

      // create element if it doesn't exist
      if (!outputArray[key]) outputArray[key] = 0;

      // increment by value
      outputArray[key] += count;
  }

  return outputArray;
}

This function will generate an object with grouped names and counts:

{
  "John": 6,
  "Jane": 8
}

To display the name of each property along with its value using ng-repeat:

<li ng-repeat="(key, value) in groupedNames">
  The total for {{key}} is {{value}}
</li>

The javascript code is relatively simple, depending on the number of name-value pairs. You can even eliminate the manual calculation button and use a $watch on values to automatically update totals with every change.

$scope.$watch('values', function() {
  $scope.groupedNames = groupByName($scope.values);
});

Check out the Demo on Plunker

Answer №3

If you want to create a TotalArray using the name of your input as the key and its count as the value, you can follow this method. Simply go through each pair in the input and determine if there is already an existing key with the same name. If there is, add the count to its current value. If not, create a new entry in the TotalArray.

Here's some pseudo code that could guide you:

inputArray = text.split('\n')
outputArray = []
for(i = 0, i< length, i++) {
    name = inputArray[i].split(',')[0]
    count = inputArray[i].split(',')[1]
    if (outputArray[name] exists) {
        outputArray[name] += count
    } else {
        outputArray[name] = count
    }
}

Now, your outputArray will display [[name1] => total_count1, [name2] => total_count2,... ]

I hope this explanation assists you in your task.

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

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

Update Tagged Page with axios Integration in NextJs 13

In the latest version of NextJS 13, we have the option to revalidate tagged pages by using the fetch function. However, what if I want to use axios instead of fetch? Is there a way to set tags with axios? At the moment, the code for setting tags using fet ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Struggling to get the ReactJS.NET MVC tutorial to function properly?

After deciding to start a new project in Visual Studio with MVC 5 and a single page app using ReactJS, I consulted the guide on the ReactJS website. Upon running the project for the first time, I encountered a syntax error due to JSX. It seemed that the b ...

A guide on implementing the grid feature in Angular.js

Looking to add the following features in my Angular grid: Paging Filtering Column-wise sorting Can anyone recommend an Angular JS grid that supports these functionalities? ...

Container for Magazines using HTML and CSS

Looking to develop a digital magazine application with smooth swipe transitions and fade in effects when swiping left and right. I attempted using jQuery.mobile, but struggled with adapting the background image height. My goal is to create a universal web ...

When using the HTML5 draw img feature, only the top 1/4 of the image will be

I am having trouble loading a full image into canvas. Currently, it only displays the top 1/4 of the image regardless of which one I use. Any help would be greatly appreciated. Here is the code snippet in question: var canvas = document.getElementById(&ap ...

Is it possible to sort a two-dimensional array within an AngularJS directive?

In my coding project, I am filling an array with objects. Is there a way to organize this array by the 'title' property? // Add items to array var item = {title: title, src: file}; images.push(item); // Can we sort it based on title? images.sor ...

Use jquery or javascript to align a button to the center

Can the vote button be centered in the script below? <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6352993.js"></script> <noscript><a href="http://polldaddy.com/poll/6352993/">This is a le ...

Protractor test freezes after attempting to click on an element

I have encountered a challenge while attempting to write a protractor test that selects an item from a custom dropdown menu. The issue arises when trying to click on an element other than the last one in the list, as it hangs and times out. Interestingly, ...

Moving from $.ajax to $http in AngularJS can improve the performance and efficiency of your

For the purpose of testing (to utilize $httpBackend), I am looking to switch my Service from using jQuery $.ajax to Angular's $http. This is how my current service is structured: app.service('myService', function() { return { getUse ...

Enhance ant design modal functionality by enabling resizing capabilities

I'm experiencing an issue with the Ant Design Modal component as it does not support resizing the modal window. I'm looking for a way to enable manual resizing of the modal window once it has been opened. Is there a solution available for this fu ...

Getting the ng-model value from a Directive's template and passing it to a different HTML file

When working with my name directive, I am unable to retrieve the value of ng-model from the template-url. team-two.html <form name="userForm" novalidate> <div name-directive></div> </form> <pre>{{userForm.firstname}}< ...

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

What is the reason behind the error "Uncaught SyntaxError: Malformed arrow function parameter list" when using "true && () => {}"?

When the code below is executed: true && () => {} it results in an error message stating: Uncaught SyntaxError: Malformed arrow function parameter list Why does this happen ? Update: I am aware that wrapping the function in parentheses reso ...

Is npm bundled with node-gyp?

I am currently experiencing an issue where running npm install locally does not produce much output when using npm v6.14.9. However, when I deploy to the server, it generates some incomprehensible messages like: gyp info spawn args ['some properties a ...

Continuously animate a series of CSS properties

Here's the code snippet I'm working with: @keyframes ball1 { 0% { transform: translateX(0px); opacity: 0%; } 50% { opacity: 100%; } 100% { transform: translateX(120px); opacity: 0%; } } @keyframes ball2 { 0 ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

Determine the total of all the values displayed in the footer of a jQuery

I am looking to show the total amount in the footer of a jquery datatable. Below is a snapshot of my datatable: https://i.stack.imgur.com/z01IL.png Here is the code snippet for my jquery datatable: for (var i = 0; i < length; i++ ) { var patient = ...