1

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:

$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].

2 Answers 2

5

You're missing return statement inside 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);

but this is showing as [null,null,null].

You should be getting [ undefined, undefined, undefined ] as nothing is returned, by default undefined is returned.


Equivalent code written using 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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.