Extracting The Most Duplicate Value From An Array In Javascript (with Jquery)
Solution 1:
Not perfect in terms of efficiency, but does the job:
var nums = [3, 7, 7, 7];
var freqs = {};
var max_index;
var max_value = -1/0; // Negative infinity.
$.each(nums, function(i, v) {
if (freqs[v] != undefined) {
freqs[v]++;
} else {
freqs[v] = 1;
}
});
$.each(freqs, function(num, freq) {
if (freq > max_value) {
max_value = freq;
max_index = num;
}
});
if (max_index != undefined) {
alert("Most common element is " + max_index + " with " + max_value + " repetition(s).");
}
Solution 2:
Here's a simpler and faster version using only JavaScript:
var arr = [3, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
alert(res + " occurs " + counts[res] + " times");
Note that this is a much more efficient since you're looping over the data once, if you're sorting very large arrays this will start to matter.
Solution 3:
Here's a quick example using javascript:
function mostFrequent(arr) {
var uniqs = {};
for(var i = 0; i < arr.length; i++) {
uniqs[arr[i]] = (uniqs[arr[i]] || 0) + 1;
}
var max = { val: arr[0], count: 1 };
for(var u in uniqs) {
if(max.count < uniqs[u]) { max = { val: u, count: uniqs[u] }; }
}
return max.val;
}
A quick note on algorithmic complexity -- because you have to look at each value in the array at least once, you cannot do better than O(n). This is assuming that you have no knowledge of the contents of the array. If you do have prior knowledge (e.g. the array is sorted and only contains 1s and 0s), then you can devise an algorithm with a run time that is some fraction of n; though technically speaking, it's complexity is still O(n).
Solution 4:
Array.prototype.mostFreq=function(){
var what, a= this.concat(), ax, freq,
count, max=0, limit= a.length/2;
while(a.length){
what= a.shift();
count=1;
while((ax= a.indexOf(what))!= -1){
a.splice(ax,1); // remove counted items
++count;
}
// if any item has more than half the array, quit countingif(count> limit) return what;
if(count> max){
freq= what;
max= count;
}
}
return freq;
}
var a=[1,1,2,5,4,2,7,7,1,1,1,3,7,7,3,4,3,7,3,5,6,2,3,1,1,7,7,2,4,3,6,7,6,6]
alert(a.mostFreq())
Solution 5:
Another solution can be based on Array.reduce():
var arr = [1,1,2,5,4,2,10,10,1,1,1,3,10,10,3,4,3,10,3,5,6,2,3,1,1,10,10,2,4,3,6,10,6,6];
var result = arr.reduce(function(acc, e) {
acc[e] = (acc[e] || 0) + 1;
if (acc[e] > acc.mostFreq.freq) {
acc.mostFreq.value = e;
acc.mostFreq.freq = acc[e];
}
return acc;
}, {"mostFreq": {"value": 0, "freq": 0}}).mostFreq;
console.log('The most duplicated elements is: ' + JSON.stringify(result));
Post a Comment for "Extracting The Most Duplicate Value From An Array In Javascript (with Jquery)"