Let’s say I have an array
var array = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];
And I want to do a check, and get true if there are 4 identical elements "A"
If I use array.includes("A"), then it looks for only one such among all and in any case returns true, but I need when there are exactly 4 such elements
Or let’s say in the same array I want to find 3 elements "B" and 2 elements "C", and return true only if there are as many of them as I’m looking for, if less, then return false
How can I do this?
>Solution :
Pulling my answer from this on stackflow.
var array = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];
const counts = {};
for (const el of arr) {
counts[el] = counts[el] ? counts[el] + 1 : 1;
}
console.log(counts["A"] > 4) // 4 or more "A"s have been found
console.log(counts["B"] === 3 && counts["C"] === 3) // exactly 3 "B"s and 2 "C"s have been found