How to validate if an element in an array is repeated? - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Example

Following is the code −

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

This will produce the following output on console −

false
false
true
raja
Published on 01-Oct-2020 10:36:18
Advertisements