如何计算AngularJS应用程序列表中特定项目的数量

时间:2016-04-10 14:26:15

标签: javascript angularjs

我正在使用以下代码尝试生成一个列表,显示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;
});

我希望[3,2,1]作为输出,但显示为[null,null,null]

2 个答案:

答案 0 :(得分:5)

您在return内遗失了map()声明。

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




  

但显示为[null,null,null]

您应该收到[ undefined, undefined, undefined ],因为没有返回任何内容,默认情况下会返回undefined

使用ES2015 arrow function编写的等效代码。

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




答案 1 :(得分:0)

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