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?