Search code examples
javascriptarraysminpromptminimum

I cant solve this: to find the minimum number from an array that is input through prompt()


I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:

    <script>
 function getMarks() {
    var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
    return marks;
  }
  var studentMarks = getMarks();
  var arrayLength = studentMarks.length;
  var studentNumber = 0;
  var msg = '';
  var i;
  for (i = 0; i < arrayLength; i++) {
    studentNumber = (i + 1);
    msg += 'student ' + studentNumber + ': ';
    msg +=  studentMarks[i] + '%' + '<br />';
  } document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>

Solution

  • I will do that in the following way:

    function getMarks() {
      var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
      return marks.split(',').map(n => Number(n));
    }
    
    var marksArray = getMarks();
    var studentMarks = Math.min(...marksArray);
    var position = marksArray.indexOf(studentMarks);
    var msg = 'Student ' + Number(position + 1) + ': ';
    document.getElementById('marks').innerHTML = msg + studentMarks +  '%';
    <p id="marks"></p>