We are required to write a JavaScript function that takes in two arguments −
An Array, say arr, of literals that may contain some repeating elements.
A number, say limit.
The function should validate that no element of the array is repeated more than limit number of times. If any element is repeated more than the limit the function should return false, true otherwise.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [4, 6, 7, 4, 2, 5, 7, 7, 4, 4, 3]; const validateElements = (arr, n) => { const counts = arr.reduce((acc, el) => { acc[el] = (acc[el] + 1) || 1; return acc; }, {}); return Object.values(counts).every(c => { return c < n; }); }; console.log(validateElements(arr, 3)); console.log(validateElements(arr, 4)); console.log(validateElements(arr, 6));
Output
The output in the console will be −
false false true