How to find the most repeated item of an array in javascript
Posted By : Vinay Tiwari | 24-Dec-2017
Here in this code, we have taken an array of finite elements. We want to show the maximum repeated number or characters. So, we have to take a counter variable which is
Now will define the code structure
var arr = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var mf = 1;
var m = 0;
var item;
for (var i = 0; i < arr.length; i++) {
for (var j = i; j < arr.length; j++) {
if (arr[i] == arr[j]) m++;
if (mf < m) {
mf = m;
item = arr[i];
}
}
m = 0;
}
alert(item + " ( " + mf + " times ) ");
Declaration
- 'arr' here is the array of finite number.
- '
mf ' is the default maximum frequency. - 'm' is used for incrementing the element and initially set to zero.
- 'item' is used for assigning the element.
Here we would select the 1st element of the given array and compare it with every element from there onwards.
Then the
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vinay Tiwari
Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.