-1

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?

baby
  • 33
  • 7

2 Answers2

2

Take a shot like this.

const myArr = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];

const findExactly = (arr, val, q) => arr.filter(x => x == val).length == q; 

// logs "true" as expected :)
console.log(findExactly(myArr, 'A', 4));

So the function findExactly receives an array, a value and a number X as the quantity. Returns a boolean if the array contains the value X times. So the example above works for the example you gave on the question "And I want to do a check, and get true if there are 4 identical elements "A"".

Luka Cerrutti
  • 667
  • 1
  • 4
  • 9
1

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

IndevSmiles
  • 737
  • 6
  • 17