arraysangularjssum

Sum arrays' columns in AngularJS


I am pretty new to AngularJS (and to development in general). I am trying to create a simple game and I am stuck with one problem.

The user can add words to a list and my script automatically associate 5 random numbers (in a specific range) to every item with the following:

$scope.randomNum = getNum();
function getNum () {
    var arr = [];
    min = 1;
    max = 5;
    for (i=0; i<5; i++) {
        arr.push(Math.floor(Math.random() * (max - min + 1)) + minEffort);
    }
    return arr;
}

I would like to dynamically get the sums of the columns of those arrays. For instance, if the user adds three words:

and these words get respectively the following random numbers:

I need to push to the page the total of every column: 7, 13, 7, 7, 5. And I also need to use those totals to run further math.

How can I do that?

EDIT I stumbled upon this filter:

app.filter('sumByKey', function () {
  return function (data, key) {
    if (typeof (data) === 'undefined' || typeof (key) === 'undefined') {
      return 0;
    }

    var sum = 0;
    for (var i = data.length - 1; i >= 0; i--) {
      sum += parseInt(data[i][key]);
    }

    return sum;
  };
});

That allows me to get the sum for a single columns with

{{items|sumByKey: 'randomNum[i]'}}

Can I reiterate it automatically for the total number of columns? Can I store the results in another array for further operations?


Solution

  • $scope.sums will contain sum of all columns. You can use it further.

    $scope.words = [];
    $scope.sums = [];
    $scope.getNum = function () {
        var arr = [];
        min = 1;
        max = 5;
        for (i = 0; i < 5; i++) {
            arr.push(Math.floor(Math.random() * (max - min + 1)) + minEffort);
        }
        return arr;
    };
    
    //add word and associate random number arrays
    $scope.add_word = function (word) {
        $scope.words.push({word_text: word, numbers: $scope.getNum()});
    };
    
    // give columns sums,no matter what how many rows are
    $scope.get_columns_sum = function () {
        angular.forEach($scope.words, function (word, key) {
            angular.forEach(word.numbers, function (number, key) {
                if (isNaN($scope.sums[key])) {
                    $scope.sums[key] = number;
                } else {
                    $scope.sums[key] = $scope.sums[key] + number;
                }
            });
        });
        console.log($scope.sums);
    };
    
    $scope.add_word('first word');
    $scope.add_word('second word');
    $scope.add_word('third word');
    $scope.get_columns_sum();