0

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.

2
  • 1
    Your question isn't clear. Read How to Ask for instructions how to fix that. Commented Feb 7, 2016 at 18:58
  • @Ian $scope.numOfCommentsCoupon. thats the array returned from the server function. i need to filter it. Commented Feb 7, 2016 at 19:00

3 Answers 3

2

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

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

Comments

0

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

Comments

0

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)

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.