3

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>

2 Answers2

1

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();
Jan
  • 8,011
  • 3
  • 38
  • 60
1

Your issue stems from the fact that you never convert your input (which you receive from prompt as a string) into an actual array.

When mode is called directly on the string, the comma is returned as being the most common because comma is the most common character in the string.

To fix this, you need to convert your string into an actual array so you're operating on the elements of the array instead of the characters of the string.

You can use the split function to split your string ("1,2,3,2") at commas into an array (["1", "2", "3", "2"]) which you can then pass to the mode function:

mode(input.split(","))
Shadowfacts
  • 1,038
  • 10
  • 22