2

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:

  • First
  • Second
  • Third

and these words get respectively the following random numbers:

  • [0,5,2,4,2]
  • [3,5,1,2,1]
  • [4,3,4,1,2]

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?

2 Answers 2

1

$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();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot mudasser. I am not sure why I am getting "undefined" for get_colums_sum()... I put my code in JSFiddle, but apparently it is not working at all: jsfiddle.net/nitecorp/n61cmkfg/2 While on my local server everything but the sum is working...
@MirkoG. you were missing to define $scope.sums in controller,which was being used in get_col_sum function. Here is plnkr plnkr.co/edit/fDgY0syOUacSXtJVBQlr?p=preview , $scope.sums is array which keeps total of all columns.
Thanks Mudasser, If I return the sum something weird happens: the first sum looks like the number of the first array are repeated twice, then the sum changes as soon as I type something in the input text field: plnkr.co/edit/ltNwhJupqfWINHc8cl1N?p=preview :(
@MirkoG. check now plnkr.co/edit/A7RCdXMUst2pZF8cN6K2?p=preview its working right, i was not making $scope.sums = [] before each new sums cycle.It is fixed now.
0

Assuming that every array has the same length (5 elements in this case) you can apply the next algorithm.

array_of_arrays will be an array of the arrays to sum, it means:

var array_to_arrays = [[0,5,2,4,2], [3,5,1,2,1], [4,3,4,1,2]];

function sumCols(array_to_arrays) {
   var sum = 0;
   var sum_cols = [];
   for(var i = 0; i < 5; i++) {
      for(var j = 0; j < array_to_arrays.length; j++) {
         sum += array_to_arrays[j][i];
      }
      sum_cols.push(sum);
      sum = 0;
   }
   return sum_cols;
} 

I created a plnkr with a example: http://plnkr.co/edit/0FElcQamh9b7nHbQDMkn?p=preview

2 Comments

Thank you Fran, how can I make this solution independent from the number of arrays? array_to_array could contain from 0 to N arrays. How do I dynamically get it?
The function is independent of array_to_arrays length. The only assumption is that every component must be equal length (five in this case).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.