Highest Value form Array

·

2 min read

PROBLEM:- A teacher wants to find the highest marks scored by a student in a class of five students. the teacher enters the marks of all five students in an array called ''marks'' .write a program that iterates through the array and finds the highest marks scored by students in the class. the highest marks must then be displayed to the teacher using the console.

Divide the problem into small Steps: -

  1. Make an array for a list of student names and marks

  2. Using an array method to get the highest marks that iterate over an array

Applying the steps:-

  1. Make an array for a list of student's names and marks

    -> Here we are making an array named Marks all student names and marks are stored in this array

     let marks = [
       {
         name: "student1",
         mark: 78,
       },
       {
         name: "student2",
         mark: 90,
       },
       {
         name: "student3",
         mark: 69,
       },
       {
         name: "student4",
         mark: 96,
       },
       {
         name: "student5",
         mark: 64,
       },
     ];
    
  2. Using an array method to get the highest marks that iterate over an array

    -> use reduce method on the array and pass two parameters 'a' and 'b' and then store them into a variable named 'highestMark'.

    reduce method is iterate over the array and checks the value in pairs. their fore reduce method requires two parameters.

    Here we use the ternary operator in the one-liner function and put one mark to another mark in greater than condition and return the value corresponding to marks. (a.mark > b.mark ? a : b).

    if the first value is greater than the second then the first value is returned and checked for the next value and so on.

    if the second value is greater than the first then the second value is returned and checked for the next pair and so on till the last pair.

    in the last combination of pairs, the bigger value is returned and stored in the 'highestMark' variable and printed to the console using concole.log().

let highestMark = marks.reduce((numOne, numTwo) =>
  numOne.mark > numTwo.mark ? numOne : numTwo
)
console.log(highestMark);