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

Acquiring variables from a JQuery Ajax request while invoking a JavaScript file

I'm currently experimenting with using JQuery Ajax to retrieve a javascript file. I need to pass some parameters to it, but I'm not entirely sure how to do so in Javascript (PHP seems easier for this). Here is my current setup: function getDocum ...

Exploring the Concept of Nested ViewModels in Knockout.js Version 3.2.0

I have a global view model that is applied to the main div and I also have other view models that I want to apply to nested elements within my main div However, I am encountering an issue: You cannot bind multiple times to the same element. Below is ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Can you include both a routerLink and a click event on the same anchor tag?

I am facing an issue with my li elements. When a user clicks on them, it should open a more detailed view in another component. However, I noticed that it takes TWO clicks to show the data I want to display. The first click opens the component with an em ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

Extracting the chosen content from a textarea using AngularJS

Greetings! I am currently experimenting with an example that involves displaying values in a text area. You can find the code on Plunker by following this link: Plunker Link <!DOCTYPE html> <html> <head> <script src="https://aj ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

How to prevent users from selecting certain options using angular's ng-options

As per the Angular documentation ng-options guidelines I tried to implement this piece of code: <select ng-model="model" ng-options="item.CODE as item.NAME disable when item.DISABLE for item in list" id="foo" name="foo" ng-change="change()"> Howe ...

Transferring mouse events from iframes to the parent document

Currently, I have a situation where my iframe is positioned over the entire HTML document. However, I am in need of finding a way to pass clicks and hover events from the iframe back to the main hosting document. Are there any potential solutions or alter ...

Discovering the art of interpreting the triumphant outcome of an Ajax request with jquery/javascript

I recently encountered a challenge with my function that deals with a short JSON string: <script id="local" type="text/javascript"> $( document ).ready(function() { $('tr').on('blur', 'td[contenteditable]', functi ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

In React, the `context` is consistently an empty object

I am facing an issue while trying to establish a context in my React App. For some reason, I am unable to access context from the children components. Here is the parent component: import React from 'react' import MenuBar from './MenuBar.js ...

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Arranging a dropdown list of options in alphabetical order using Javascript

Could you assist me in sorting my select list alphabetically? Below is the code I currently have:- $.getJSON("php/countryBorders.geo.json", (data) => { $select.html(""); for (let i = 0; i < data["features"].leng ...

Enable modification of form field once a personalized dynamic stamp has been applied

I currently have a functional custom dynamic stamp that includes multiple input fields prompting the user. My goal now is to integrate a form text field onto the stamp after it has been rendered. For example, if someone stamps everything except for the led ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...