Amir.O Amir.O - 1 month ago 5
Javascript Question

Calling a function inside another function in JavaScript

I have defined a function named larger to find the larger number between two arguments (num1, num2). Now I want to use this function inside another function called "largest" which gets an array and return the largest number of that array, but I`ve got stuck. Can anybody help me with that?
Here is my codes:

function larger(num1, num2){
var largerNumber = 0;
if (num1 > num2){
largerNumber = num1;
} else {
largerNumber = num2;
}
return largerNumber;
}

function largest(array){
for (var i = 0; i < array.length ; i++){
for (var j = 0; j < array.length ; j++){
if (array[i] != array[j]){
//I don`t know if I am doing it right
}
}
}
}

Answer

Iterate through the array once, keeping only the largest:

function larger(num1, num2){
  var largerNumber = 0;
  if (num1 > num2){
   largerNumber = num1;
  } else {
      largerNumber = num2;
  }
return largerNumber;
}

function largest(array){
 let largestNumber = array[0];
 for (var i = 1; i < array.length ; i++){
  largestNumber = larger(largestNumber, array[i]);
 }
 return largestNumber;
}

var test = [1, 53, 352, 22, 351, 333, 123, 5, 25, 96];
console.log(largest(test));

Comments