Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  65] [ 5]  / answers: 1 / hits: 26037  / 7 Years ago, thu, december 21, 2017, 12:00:00

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,
},
]

More From » arrays

 Answers
34

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




[#55618] Tuesday, December 19, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
oliverg

Total Points: 453
Total Questions: 101
Total Answers: 100

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;