Skip to content
the poor coder

check if frequent array js

Poor Man
Published
Reading time
2 min read
On this page

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.

Text

function checkFrequent(arr, el) {
   var count = 0;
   for (var i = 0; i < arr.length; i++) {
      if (arr[i] === el) {
         count++;
         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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC