Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the item that appears the most times in an array

Tags:

var store = ['1','2','2','3','4']; 

I want to find out that 2 appear the most in the array. How do I go about doing that?

like image 904
p0larBoy Avatar asked Sep 24 '10 03:09

p0larBoy


People also ask

How do you find the most repeated item in an array?

A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far.

How do you find out how many times an item appears in an array?

To check how many times an element appears in an array:Declare a count variable and set its value to 0 . Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .

How do you find the maximum occurring element in a list?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.


2 Answers

I would do something like:

var store = ['1','2','2','3','4']; var frequency = {};  // array of frequency. var max = 0;  // holds the max frequency. var result;   // holds the max frequency element. for(var v in store) {         frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.         if(frequency[store[v]] > max) { // is this frequency > max so far ?                 max = frequency[store[v]];  // update max.                 result = store[v];          // update result.         } } 
like image 194
codaddict Avatar answered Oct 19 '22 17:10

codaddict


Solution with emphasis to Array.prototype.forEach and the problem of getting more than one key if the max count is shared among more items.

Edit: Proposal with one loop, only.

var store = ['1', '2', '2', '3', '4', '5', '5'],      distribution = {},      max = 0,      result = [];    store.forEach(function (a) {      distribution[a] = (distribution[a] || 0) + 1;      if (distribution[a] > max) {          max = distribution[a];          result = [a];          return;      }      if (distribution[a] === max) {          result.push(a);      }  });  console.log('max: ' + max);  console.log('key/s with max count: ' + JSON.stringify(result));  console.log(distribution);
like image 23
Nina Scholz Avatar answered Oct 19 '22 15:10

Nina Scholz