- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to validate if an element in an array is repeated? - 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
- Related Articles
- How to validate an array in Laravel?
- How to count number of occurrences of repeated names in an array - JavaScript?
- How to search for an element in JavaScript array?
- Adding an element in an array using Javascript
- Removing an element from an Array in Javascript
- Write a Java program to find the first array element whose value is repeated an integer array?
- How do we check if an object is an array in Javascript?
- How to check if a variable is an array in JavaScript?
- Searching an element in Javascript Array
- How to find out if an element is hidden with JavaScript?
- How to insert an element into all positions in an array using recursion - JavaScript?
- How to validate if JTable has an empty cell in Java?
- How to remove every Nth element from an array JavaScript?
- Java Program to Remove Repeated Element from An ArrayList
- How to find the min/max element of an Array in JavaScript?

Advertisements