Get the element with the highest occurrence in an array

后端 未结 30 1736
野性不改
野性不改 2020-11-22 11:17

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

For example, in

[\'pear\', \'a         


        
30条回答
  •  青春惊慌失措
    2020-11-22 12:02

    Another JS solution from: https://www.w3resource.com/javascript-exercises/javascript-array-exercise-8.php

    Can try this too:

    let arr =['pear', 'apple', 'orange', 'apple'];
    
    function findMostFrequent(arr) {
      let mf = 1;
      let m = 0;
      let item;
    
      for (let i = 0; i < arr.length; i++) {
        for (let j = i; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            m++;
            if (m > mf) {
              mf = m;
              item = arr[i];
            }
          }
        }
        m = 0;
      }
    
      return item;
    }
    
    findMostFrequent(arr); // apple
    

提交回复
热议问题