0

I'm developing an AngularJS application, working with Parse.com as the backend.

What I'm trying to achieve:
I have multiple answer scores (values) stored within an Array, I want to be able to add up each value within each Array and display the total of each set.

e.g
Set 1 [1,2,3] = 6 Points
Set 2 [1,1,1,1] = 4 Points

Current Problems:
No matter what example I attempt to use I can't seem to get this working.

Any help / advice would be helpful!

Controller JS:

var dashApp = angular.module('dashApp.controllers', ['chart.js']);
dashApp.controller("dashboardCtrl", function($scope, $http, $filter) {
    $scope.parseRecommend = [];
    // Question Answer Array
    $scope.parseQ1P1 = [];
    $scope.parseQ1P2 = [];
    $scope.parseQ2P1 = [];
    $scope.parseQ2P2 = [];
    $scope.parseQ3P1 = [];
    $scope.parseQ4P1 = [];
    $scope.parseQ5P1 = [];
    var hashmap = {};
    $http({
            method: 'GET',
            url: 'https://api.parse.com/1/classes/Customers',
            headers: {
                'X-Parse-Application-Id': 'xxx',
                'X-Parse-REST-API-Key': 'xxx'
            }
        })
        .success(function(data, error) {
            $scope.parseResults = data.results;
            // Widget Data
            angular.forEach($scope.parseResults, function(results) {
                $scope.parseRecommend.push(results.question_4_p1);
                // Get Question Anwsers
                $scope.parseQ1P1.push(results.question_1_p1);
                $scope.parseQ1P2.push(results.question_1_p2);
                $scope.parseQ2P1.push(results.question_2_p1);
                $scope.parseQ2P2.push(results.question_2_p2);
                $scope.parseQ3P1.push(results.question_3_p1);
                $scope.parseQ4P1.push(results.question_4_p1);
                $scope.parseQ5P1.push(results.question_5_p1);
            });
            $scope.parseRecommend.forEach(function(elm) {
                hashmap.hasOwnProperty(elm) ? ++hashmap[elm] : hashmap[elm] = 1
            });
            // Widget One
            var yesAmount = hashmap.yes;
            var noAmount = hashmap.no;
            $scope.widgetone_data = [yesAmount, noAmount];
            $scope.widgetone_label = ["Yes", "No"];
            // Widget Two
            $scope.widgettwo_label = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10'];
            $scope.widgettwo_data = [
                [65, 59, 100, 81, 56, 55, 40, 44, 87, 12],
                [22, 33, 44, 11, 55, 6, 97, 5, 72, 45]
            ];
        })
        .error(function(data, error) {
            alert('Failed, error code: ' + error.message);
        });
});

4 Answers 4

3

here:

var Set1 = [1,2,3],
    Set2 = [1,1,1,1];

$scope.tot1 = Set1.reduce((p,c) => p + c); //6
$scope.tot2 = Set2.reduce((p,c) => p + c); //4

or if nested in Array like this:

var Sets = [];
Sets.push(Set1);
Sets.push(Set2);

var result = Sets.map(val => val.reduce((p,c) => p+c));
// result == [6, 4]

ps. if you wonder p and c stands for previous and current, here is relevant documentation

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Webdeuvet! This worked perfectly and thank you for the extended documentation!
Afternoon @Webduvet I've noticed the following doesn't work within Chrome - reduce( (p,c) => p + c );
that's perhaps because of ES6 arrow function. Try using ES5 .reduce(function(p,c){return p + c;})
0

As i can see in you code you want to sum values inside and array of array.Then there are lot of ways.You can make an array of array like in example One you can look into the example i am doing for you in fiddle. Have a look of it. If there is any mismatch then please reply i will help you in that.

Look into JsFiddle

<div ng-app="app" ng-controller="demoController">
    {{sum}}
</div>

var app= angular.module("app",[]);
app.controller('demoController', ['$scope', 
  function($scope) {
    $scope.sum = 0;
    $scope.widgettwo_data = [
                [65, 59, 100, 81, 56, 55, 40, 44, 87, 12],
                [22, 33, 44, 11, 55, 6, 97, 5, 72, 45]
            ];

      angular.forEach($scope.widgettwo_data,function(arr){
          if(angular.isArray(arr)){
              angular.forEach(arr,function(num){
                $scope.sum += num;
              });               
          }
          else{
            $scope.sum += num;
          }
      });

}]);

Comments

0

You could create a function within the scope that totals them:

$scope.set_1 = [1,2,3];
$scope.set_2 = [1,1,1,1];

$scope.totalArray = function(passed_array){
    var total = 0;

    for (var index=0; index<passed_array.length; index++) {
       total += passed_array[index];
    }
    return total;
}

$scope.total_1 = $scope.totalArray($scope.set_1);
$scope.total_2 = $scope.totalArray($scope.set_2);

Comments

0

I made a slightly change based on @Akshay's code. It calculates the sum of individual array and display individually.

Link to JSFiddle

Result

Array 0 sum: 599

Array 1 sum: 390

html

<div ng-app="app" ng-controller="demoController">
  <div ng-repeat="value in arraySum track by $index">Array {{$index}} sum: {{value.sum}}</div>
</div>

js

 var app= angular.module("app",[]);
 app.controller('demoController', ['$scope', function($scope) {
    $scope.sum = 0;
    $scope.arraySum = [];
    $scope.widgettwo_data = [
                [65, 59, 100, 81, 56, 55, 40, 44, 87, 12],
                [22, 33, 44, 11, 55, 6, 97, 5, 72, 45]
            ];
      angular.forEach($scope.widgettwo_data,function(arr){
          $scope.sum = 0;
          if(angular.isArray(arr)){
              angular.forEach(arr,function(num){
                $scope.sum += num;
              });
              $scope.arraySum.push({
                sum: $scope.sum
              });
          }
          else{
            $scope.sum += num;
            $scope.arraySum.push({
                sum: $scope.sum
            });  
          }
      });
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.