Get the element with the highest occurrence in an array
This is just the mode. Here's a quick, non-optimized solution. It should be O(n).
function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
Get the item that appears the most times in an array
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.
}
}
get most occurring elements in array JavaScript
You can count the items with reduce
and find the maximum occurring count. Then you can filter any keys that have that count:
let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];
let counts = arr.reduce((a, c) => { a[c] = (a[c] || 0) + 1; return a;}, {});let maxCount = Math.max(...Object.values(counts));let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);
console.log(mostFrequent);
How to find an item in array which has the most occurrences
First build a hash mapping each value in the array to its frequency…
arr = [1, 1, 1, 2, 3]
freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}
… then use the frequency table to find the element with the highest frequency:
arr.max_by { |v| freq[v] }
#=> 1
Highest occurrence in an array or first selected
You could use something like this:
function mostFrequent(array) {
var map = array.map(function(a) {
return array.filter(function(b) {
return a === b;
}).length;
});
return array[map.indexOf(Math.max.apply(null, map))];
}
First it creates a map of occurrences of all the values. Next just check with Math.max
which one is the highest. Check the indexOf
for the first value that has that highest occurences and return the value of that index in the original array.
ES2015
If ES2015 is an option, you could use this one. It's less code.
function mostFrequent(array) {
let map = array.map((a) => array.filter((b) => a === b).length);
return array[map.indexOf(Math.max.apply(null, map))];
}
And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map)
for Math.max(...map)
!
Counting the occurrences / frequency of array elements
const arr = [2, 2, 5, 2, 2, 2, 4, 5, 5, 9];
function foo (array) {
let a = [],
b = [],
arr = [...array], // clone array so we don't change the original when using .sort()
prev;
arr.sort();
for (let element of arr) {
if (element !== prev) {
a.push(element);
b.push(1);
}
else ++b[b.length - 1];
prev = element;
}
return [a, b];
}
const result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')
console.log(arr)
Related Topics
How to Install a Gem or Update Rubygems If It Fails With a Permissions Error
Why Are Exclamation Marks Used in Ruby Methods
When to Use Lambda, When to Use Proc.New
How to Search File Text For a Pattern and Replace It With a Given Value
Disable Activerecord For Rails 4
Ruby: Kind_Of? Vs. Instance_Of? Vs. Is_A
How to Download a File from a Url and Save It in Rails
Pressing Ctrl + a in Selenium Webdriver
Is There a Performance Gain in Using Single Quotes VS Double Quotes in Ruby
Ruby/Ruby on Rails Memory Leak Detection
How Does the Magic Comment ( # Encoding: Utf-8 ) in Ruby Work
How to Override a Setter Method in Ruby on Rails
Rails Activerecord: Find All Users Except Current User