

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- How do we check if an object is an array in Javascript?
- How to find out if an element is hidden with JavaScript?
- How to check if a variable is an array in JavaScript?
- Adding an element in an array using Javascript
- Removing an element from an Array in Javascript
- Searching an element in Javascript Array
- How to search for an element in JavaScript array?
- How to validate if JTable has an empty cell in Java?
- Write a Java program to find the first array element whose value is repeated an integer array?
- How to count number of occurrences of repeated names in an array - JavaScript?
- Java Program to Remove Repeated Element from An ArrayList
- Determining If an Object Is an Array in Java
- How to check if an element is visible with WebDriver?
- How do I check if an array includes an object in JavaScript?
- Apply an IF condition to every element in an HTML table with JavaScript?
Advertisements