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?
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.
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 .
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.
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. } }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With