Home > front end >  true if the specified number of identical elements of the array is found
true if the specified number of identical elements of the array is found

Time:08-19

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?

CodePudding user response:

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"".

CodePudding user response:

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

  • Related