Search code examples
javascriptfunctionmeanmedian

How can I spilt a text field input so I can calculate median, mode mean and Standard Deviation of the data?


I want to calculate the median, mode, Mean and Standard Deviation of the datain in javascript but I couldn't spilt my input in the textfields so it would be like this 1 2 3 4 5 instead of 12345.

I have tried split method but it doesn't seem to work.

function mean(values) {
  var total = 0,
    i, results;
  for (i = 0; i < values.length; i += 1) {
    total += values[i];
  }
  results = total / values.length;
  document.getElementById("meanOutput").innerHTML = results;
}

function mode() {
  document.getElementById("modeOutput").innerHTML = "Fahad!";
}

function median() {
  document.getElementById("medianOutput").innerHTML = "Nasser";
}

function stdv() {
  document.getElementById("stdvOutput").innerHTML = "Alqahtani";
}
Mean: <input type="text" id="meanText"> Median:
<input type="text" id="medianText"> Mode:
<input type="text" id="ModeText"> Standard Deviation of the data:<input type="text" id="STDV">

<p id="meanOutput"></p>
<p id="modeOutput"></p>
<p id="medianOutput"></p>
<p id="stdvOutput"></p>



<button onclick="mean(document.getElementById('meanText').value); median(); mode(); stdv();">Calculate</button>

I expect that the text-fields input accepts 1 2 3 4 5 and calculate it instead of displaying NaN.


Solution

  • Issue is related to type conversion that is string type to integer, you need to parse your input numbers so that you can perform mathematical calculations, and
    Before type conversion you need to convert your input(different numbers with space separated, Eg-22 23 24) to a array of substrings which can be achieved using split function in javascript. Particularly in your case you need to split on the basis of spaces in your inputs. Rest is all good in your code.

    Hope, this helps you out.

    Code change will only be

        function mean(values) {
           var total = 0,
           i, results;
           var arraySubstrings = values.split(' ');
           for (i = 0; i < arraySubstrings.length; i += 1) {
              total += parseInt(arraySubstrings[i]);
           }
    
        results = total / arraySubstrings.length;   
        document.getElementById("meanOutput").innerHTML = results;
       }