Search code examples
javascriptarraysfunction

How to count all objects in an array that match a condition?


How can I count all objects in an array that match a condition: is_read == true?

This is how my array looks like:

[
  {
    "id": 1,
    "is_read": true,
  },
  {
    "id": 2,
    "is_read": true,
  },
  {
    "id": 3,
    "is_read": false,
  },
  {
    "id": 4,
    "is_read": true,
  },
]

Solution

  • Just use filter method by passing a callback function and use length property applied for the result of filtering.

    let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
    length = data.filter(function(item){
      return item.is_read;
    }).length;
    console.log(length);

    You can also use a lambda expression.

     let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
    length = data.filter(d => d.is_read).length;
    console.log(length);