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,
},
]
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
To check how many times an element appears in an array:Declare a count variable and set its value to 0 . Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .
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));
Using Array.reduce
const r = (sum, obj) => sum + (obj.is_read == true ? 1 : 0);
const count = arr.reduce(r, 0);
console.log(count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With