check if frequent array js

Check if frequent array js

If you are working with arrays in JavaScript, you may need to check if a particular element is repeated frequently or not. There are different ways to achieve this, and some of them are as follows:

Method 1: Using the indexOf() method and a for loop

The first method is to use the indexOf() method and a for loop to check if an element is repeated in an array. The indexOf() method returns the first index at which a given element can be found in an array, or -1 if it is not present. We can use this method along with a for loop to iterate through the array and check if each element is repeated.

function checkFrequent(arr, el) {
   var count = 0;
   for (var i = 0; i < arr.length; i++) {
      if (arr[i] === el) {
         if (count > 1) {
            return true;
   return false;

var arr = [1, 2, 3, 4, 5, 5, 6, 7];
var el = 5;

var isFrequent = checkFrequent(arr, el);

console.log(isFrequent); // true

Method 2: Using the filter() method and a length comparison

The second method is to use the filter() method to get all occurrences of an element in an array and then compare its length with a threshold value. If the length is greater than or equal to the threshold value, then the element is considered frequent.

function checkFrequent(arr, el, threshold) {
   var occurences = arr.filter(function(value) {
      return value === el;

   return occurences.length >= threshold;

var arr = [1, 2, 3, 4, 5, 5, 6, 7];
var el = 5;
var threshold = 2;

var isFrequent = checkFrequent(arr, el, threshold);

console.log(isFrequent); // true

Both of these methods can help you check if an element is repeated frequently in an array. You can choose the one that suits your needs and use it in your code. Remember to test your code thoroughly to ensure that it works as expected.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]