Search code examples
javascripthtmlsyntax-errormode

Highest occurrence in javascript


Hi my knowledge on javascript is very limited and basic. Basically below is I will prompt a pop-up that displays the answer to the value. The thing is from the coding I found below if I had to insert an array lets say 1,2,3,2 the output would be , since it has the highest occurrence in the array. Is there a way to edit this code so that the answer to the input above would be 2

I have done my fair share of research:

Here are the links:

Code:

<script type="text/javascript">
    function evaluate() {
      var input = prompt("Please enter your input");
      var array = new Array();

     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;
}
      document.writeln("Your calculation is: ");
      document.writeln(mode(input) + " with a starting input string of: " + input);

    }
  </script>
      <script type="text/javascript">
    evaluate();
  </script>

Solution

  • You want to convert the string '1,2,3,2' into the array [ 1, 2, 3, 2 ] first. this can be done with the split function. You probably also want to trim each element in case someone formats them with a space.

    function evaluate() {
      const input = prompt("Please enter the array of integers")
        .split(',')
        .map(item => item.trim());
    
      function mode(items) {
        const counts = items
          .reduce((counts, item) => {
            const currentItemCount = counts.get(item) || 0;
            return counts.set(item, currentItemCount + 1);
          }, new Map());
        const maxEntry = Array.from(counts.entries())
          .reduce((maxEntry, entry) => {
            return entry[1] > maxEntry[1] ? entry : maxEntry;
          });
        return maxEntry[0];
      }
      
      document.writeln("Your calculation is: ");
      document.writeln(mode(input) + " with a starting input string of: " + input);
    }
    
    evaluate();