[英]How to count number of particular items in a list in AngularJS app
I am using the following code to try and generate a list showing the count of each item in the letters
list within an AngularJS controller: 我正在使用以下代码尝试生成一个列表,该列表显示AngularJS控制器的
letters
列表中每个项目的计数:
$scope.letters = ['a','b','c'];
$scope.letterdata = ['a','b','a','c','b','a'];
$scope.counts = $scope.letters.map(function (x) {
$scope.letterdata.filter(function (y) {
return (x == y);
}).length;
});
I would like to get [3,2,1]
as the output, but this is showing as [null,null,null]
. 我想获取
[3,2,1]
作为输出,但这显示为[null,null,null]
。
You're missing return
statement inside map()
. 您缺少
map()
return
语句。
$scope.counts = $scope.letters.map(function (x) {
return $scope.letterdata.filter(function (y) {
^^^^^^
return (x == y);
}).length;
});
var letters = ['a', 'b', 'c']; var letterdata = ['a', 'b', 'a', 'c', 'b', 'a']; var counts = letters.map(function (x) { return letterdata.filter(function (y) { return(x == y); }).length; }); console.log(counts);
but this is showing as
[null,null,null]
.但这显示为
[null,null,null]
。
You should be getting [ undefined, undefined, undefined ]
as nothing is returned, by default undefined
is returned. 您应该得到
[ undefined, undefined, undefined ]
因为什么都不会返回,默认情况下会返回undefined
。
Equivalent code written using ES2015 arrow function . 使用ES2015 箭头功能编写的等效代码。
$scope.letters.map(x => $scope.letterdata.filter(y => x == y).length)
var letters = ['a', 'b', 'c']; var letterdata = ['a', 'b', 'a', 'c', 'b', 'a']; var counts = letters.map(x => letterdata.filter(y => x == y).length); console.log(counts);
var list = ['a', 'b', 'c'];
var data = ['a', 'b', 'a', 'c', 'b', 'a'];
_.reduce(list, function(counts, value) {
counts.push(_.size(data) - _.size(_.without(data, value)));
return counts;
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.