Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

true if the specified number of identical elements of the array is found

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading