0

I am trying to find and return the largest number in each array using a for loop but every time I try to print something I get an error. I have tried using the following JS array methods: Math.max, Math.max.apply but I cannot get them to work.

My code is below. Any help will be appreciated and if you could please point out what I am doing wrong, that would be really great. Thanks in advance!

Question: numbers is an array of integers. Find and return the largest integer.

My code:

function largestNumber(numbers) { // this function was given by the quiz writer, my code starts below "code here"
  // code here

  numbers = [1, 2, 3, 4, 5];
  for(let i = 0; i < numbers.length; i++){
    let largest = 0;
    if(numbers[i] > largest){
      largest = largest.numbers[i];
    }
  }
  return largest;
}

console.log(largestNumber);
babycoder
  • 184
  • 1
  • 2
  • 17
  • 1
    you are setting `largest` back to 0 on every iteration of the loop. Put the declaration of `largest` outside of your for loop. – CRice Nov 14 '17 at 02:15
  • Also, I think you meant to write `largest = numbers[i];` – 4castle Nov 14 '17 at 02:19
  • *"Multi-dimensional arrays... in **each** array"* - The code shown processes one single-dimensional array. Should the `numbers` argument actually allow for multi-dimensional arrays, or...? Also `console.log(largestNumber);` doesn't *call* your function, you'd need `console.log(largestNumber());`, or really you should be passing the numbers in as an argument, so `largestNumber([1,2,3,4])`. – nnnnnn Nov 14 '17 at 02:29

1 Answers1

2

You can use Math.max.apply as below sample to find max value in array

function largestNumber(numbers) {
    return Math.max.apply(null, numbers);
}
console.log(largestNumber([1, 2, 3, 4, 5]));
artgb
  • 3,177
  • 6
  • 19
  • 36
i3lai3la
  • 980
  • 6
  • 10
  • It's noteworthy to mention the new and cleaner syntax for the same operation. `Math.max(...numbers)` – Andrew Nov 14 '17 at 03:45
  • But be careful, exist practical limit to count of arguments passed to function in [different browsers](https://stackoverflow.com/a/22747272/3047033) – RQman Nov 14 '17 at 06:49