How to count all objects in an array that match a condition?
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);
Filter
const count = (arr, condition) => arr.filter(condition).length;
const arr = [ { is_read: true }, { is_read: false} ]
console.log(count(arr, (o) => o.is_read));
Array#reduce
const count = (arr, condition) => arr.reduce((acc, c) => condition(c) ? ++acc : acc, 0);
const arr = [ { is_read: true }, { is_read: false } ]
console.log(count(arr, (o) => o.is_read));
Recursive
const count = ([first, ...rest], condition, acc = 0) =>
(condition(first) && ++acc,
rest.length ? count(rest, condition, acc) : acc);
const arr = [ { is_read: true }, { is_read: false } ]
console.log(count(arr, (o) => o.is_read));
Use array filter method.
//ES6
const arr = [
{
"id": 1,
"is_read": true,
},
{
"id": 2,
"is_read": true,
},
{
"id": 3,
"is_read": false,
},
{
"id": 4,
"is_read": true,
},
]
const size = arr.filter(obj => obj.is_read).length