const count = (arr, val) => arr.filter(n => n === val).length;
// или
const count = (arr, val) => arr.reduce((acc, n) => acc + (n === val), 0);
Можно и в более общем виде - считаем всё:
function Counter(data, key = n => n) {
const counted = new Map;
for (const n of data) {
const k = key(n);
counted.set(k, (counted.get(k) ?? 0) + 1);
}
return k => counted.get(k) ?? 0;
}
Использовать можно так:
const arr = [ 1, 1, NaN, 1, 2, NaN, 9, NaN, NaN, 9, 7, 'hello, world!!', 'hello, world!!' ];
const counted = Counter(arr);
console.log(counted(1)); // 3
console.log(counted(NaN)); // 4
console.log(counted('hello, world!!')); // 2
console.log(counted(10)); // 0
Или так:
<span class="color">red</span>
<span class="color">green</span>
<span class="color">red</span>
<span class="color">red</span>
const counted = Counter(document.querySelectorAll('.color'), el => el.innerText);
console.log(counted('red')); // 3
console.log(counted('blue')); // 0