count specific elements in array javascript code example
Example 1: javascript Count the occurrences of a value in an array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([2, 1, 3, 3, 2, 3], 2);
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a');
Example 2: typescript count array condition
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)