0

I understand that a loop repeats itself for a specified number of times, but how do I make so that it reads through the entire array and returns a certain value? I'm trying to return the largest value for two test questions, but the only result I'm getting is the first value of the array.

function question1(numberArray) {
  for (let i = 0; i < numberArray.length; i = i + 1) {
    number = numberArray[i];
    return number;
  }
}

function testQuestion1() {
  let testArray = [10, 45, 33, 67, 433, 33];
  let answer1 = question1(testArray);
  if(question1(testArray) == 433) {
    console.log("Question 1:Found the largest");
  } else {
    console.log("Question1: For array ", testArray, " returned ", answer1, "Which is not the largest");
  }

  let testArray2 = [10, -900, 3000, 22, 33, 67, 433, 33];
  let answer2 = question1(testArray);
  if(question1(testArray2) == 3000) {
    console.log("Question 1: Found the largest");
  } else {
    console.log("Question 1: For array ", testArray2, " returned ", answer2, "Which is not the largest");
  }
}
iAmOren
  • 2,760
  • 2
  • 11
  • 23
Simon Lee
  • 11
  • 1

1 Answers1

0

Using Math.max with Array spread operator (also in link):

function myMax(numberArray) {
  return Math.max(...numberArray);
}

Using for loops and a max variable:

function myMax(numberArray) {
  var max=-Infinity;
  for(var i=0; i<numberArray.length; i++)
    if(numberArray[i]>max)
      max=numberArray[i];
  return max;
}

Using reduce:

function myMax(numberArray) {
  return numberArray.reduce((max, arrayItem)=>Math.max(max, arrayItem),-Infinity);
}

In all cases, if numberArray is empty, -Infinity will be returned.

iAmOren
  • 2,760
  • 2
  • 11
  • 23