
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate If an Element in an Array is Repeated in JavaScript
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
Advertisements