Reputation: 13
I want to validate that a string within an array is not repeated more than 3 times, that is:
let array = ['A', 'A', 'A', 'B']
let array2 = ['A', 'A', 'A', 'A', 'B'] <-- Not valid
That the code does not continue to work, if the array it receives has values that are repeated those times
Thank you
Upvotes: 1
Views: 86
Reputation: 6525
You can use array.some() in combination with array.filter() to check if a value only exists an x amount of times.
const array = ['A', 'A', 'A', 'B'];
const array2 = ['A', 'A', 'A', 'A', 'B'];
const isValid = (arr, limit) => {
return !arr.some((char) => (
arr.filter((ch) => ch === char).length > limit
// use the next line for a case insensitive check
// arr.filter((ch) => ch.toLowerCase() === char.toLowerCase()).length > limit
));
}
console.log(isValid(array, 3));
console.log(isValid(array2, 3));
Upvotes: 3
Reputation: 6757
You can count all the letters using reduce and then check those, like so:
let array = ['A', 'A', 'A', 'B'];
let array2 = ['A', 'A', 'A', 'A', 'B'];
const allElementsExistUpToN = (arr, n) => {
const counts = arr.reduce((acc, el) => {
acc[el] = acc[el] == undefined ? 1 : acc[el] +1;
return acc;
}, {});
return !Object.values(counts).some(c => c > n);
}
console.log(allElementsExistUpToN(array, 3));
console.log(allElementsExistUpToN(array2, 3));
Upvotes: 0
Reputation: 386756
You could take a closure over the count of the last string and check the count or reset the count to one.
const
check = array => array.every(
(c => (v, i, { [i - 1]: l }) => l === v ? c++ < 3 : (c = 1))
(0)
);
console.log(check(['A', 'A', 'A', 'B']));
console.log(check(['A', 'A', 'A', 'A', 'B']));
Upvotes: 0