Reputation: 716
I have a variable which is an array of comments.
$scope.numOfCommentsCoupon
What i would like to have is a variable which is a count of the Comments inside the array that have a "couponId
" of a certain value.
Here is the Comment Model
var CommentSchema = new Schema({
created: {
type: Date,
default: Date.now
},
couponId: {
type: String,
trim: true
}
});
So i need to filter it and then count it but im not sure how to.
Upvotes: 0
Views: 53
Reputation: 9221
Youd could use reduce
method on the array to get the count of coupons whose couponId
is equals to a given string:
var comments = [
{
couponId : "1"
},
{
couponId : "2"
}
];
var couponIdToCount = "2";
var count = comments.reduce(function(previous, current) {
return current.couponId == couponIdToCount ? previous + 1: previous;
}, 0);
console.log(count)
Upvotes: 0
Reputation: 606
I think I follow what you're trying to do and you can use array.filter
It would look like this:
var currentCouponId = 1;
var matching = yourArray.filter(function (element) { return element.couponId == 1; });
console.log(matching.length);
Upvotes: 0
Reputation: 6824
If you have an array of comments, to do that, you could do something like this
var count = 0;
comments.filter(function(comment,index,array){
if (comment.couponId === "some_value") {
count++;
}
});
Or you could just iterate over it using the for loop. Pretty straightforward stuff to implement
Upvotes: 2