Asked  7 Months ago    Answers:  5   Viewed   21 times

I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

['pear', 'apple', 'orange', 'apple']

the 'apple' element is the most frequent one.

 Answers

38

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;
}
Tuesday, June 1, 2021
 
danjah
answered 7 Months ago
73

Creates a local undefined in case someone redefines undefined somewhere in the scope chain.

Also provides a faster lookup since undefined is a global property, so the scope chain traversal is reduced.

Thursday, June 24, 2021
 
Amber
answered 6 Months ago
49

As commented before:

  • Create an array of keys: Object.keys(object)
  • Sort this array based on value: sort((a,b)=> object[b] - object[a])
  • Get necessary values: keys.slice(0,n)

var value = {2:1,53:2,56:4,57:9,61:2,62:16,63:2,398:24};

function getKeysWithHighestValue(o, n){
  var keys = Object.keys(o);
  keys.sort(function(a,b){
    return o[b] - o[a];
  })
  console.log(keys);
  return keys.slice(0,n);
}

console.log(getKeysWithHighestValue(value, 4))
Friday, July 30, 2021
 
Magnanimity
answered 5 Months ago
98

You can use findIndex here

check this snippet

var array = [400, 4000, 400, 400, 4000];
var index=array.findIndex(function(number) {
  return number > 400;
});
console.log(index);
Tuesday, September 21, 2021
 
adizone
answered 3 Months ago
49

Browser detection is unfortunately still necessary for things like video and audio since all browsers promote different formats. I think you'll find your answer here, Natto:

http://diveintohtml5.info/detect.html

Sunday, October 3, 2021
 
Atomble
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share