AngularJS计算每个数组的总和

时间:2015-08-13 19:06:19

标签: arrays angularjs

我正在开发一个AngularJS应用程序,使用Parse.com作为后端。

我想要实现的目标:
我有一个存储在数组中的多个答案分数(值),我希望能够在每个数组中添加每个值并显示每个数组的总和。

例如 设置1 [1,2,3] = 6点
设置2 [1,1,1,1] = 4分

当前问题:
无论我尝试使用什么样的例子,我似乎都无法实现这一点。

任何帮助/建议都会有所帮助!

控制器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 个答案:

答案 0 :(得分:3)

这里:

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

或嵌套在Array中,如下所示:

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

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

PS。如果你想知道p和c代表先前和当前, 这里是相关的documentation

答案 1 :(得分:0)

您可以在范围内创建一个总计它们的函数:

$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);

答案 2 :(得分:0)

正如我在你的代码中看到的那样,你想要对数组里面的值和数组进行求和。然后有很多方法。你可以像示例中那样创建一个数组数组 你可以看一下我在小提琴里为你做的例子。 看看吧。 如果有任何不匹配,请回复我会帮助您。

https://www.mozilla.org/en-US/firefox/geolocation/

<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;
          }
      });

}]);

答案 3 :(得分:0)

我根据@ Akshay的代码做了一些改动。 它分别计算单个数组和显示的总和。

Link to JSFiddle

结果

数组0总和:599

数组1总和:390

HTML

 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
            });  
          }
      });
}]);

JS

SELECT
  "defect"."BG_BUG_ID" AS "Defect",
  "defect"."BG_STATUS" AS "Status",
  "defect"."BG_SEVERITY" AS "Severity",
  "defect"."BG_PRIORITY" AS "Priority",
  "defect"."BG_USER_03" AS "Category",
  "defect"."BG_USER_01" AS "Modules",
  "defect"."BG_USER_08" AS "EFD",
  "defect"."BG_USER_02" AS "Region",
  "defect"."BG_SUMMARY" AS "Summary",
  "defect"."BG_DETECTED_BY" AS "Detected By",
  "audit_log"."AU_ACTION" AS "Action",
  "audit_log"."AU_USER" AS "User",
  "audit_property"."AP_OLD_VALUE" AS "Old Value",
  "audit_property"."AP_NEW_VALUE" AS "New Value",
  "audit_log"."AU_TIME" AS "Change Time",
  "audit_property"."AP_PROPERTY_NAME" AS "Change Area"
FROM
  BUG "defect"
  INNER JOIN AUDIT_LOG "audit_log" ON "defect"."BG_BUG_ID" = "audit_log"."AU_ENTITY_ID"
  INNER JOIN AUDIT_PROPERTIES "audit_property" ON "audit_log"."AU_ACTION_ID" = "audit_property"."AP_ACTION_ID"
WHERE
    "audit_log"."AU_ENTITY_TYPE" = 'BUG'