Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  11] [ 3]  / answers: 1 / hits: 34304  / 5 Years ago, mon, february 11, 2019, 12:00:00

Create a function called biggestNumberInArray().


That takes an array as a parameter and returns the biggest number.


Here is an array


const array = [-1, 0, 3, 100, 99, 2, 99]

What I try in my JavaScript code:


 function biggestNumberInArray(arr) {
for (let i = 0; i < array.length; i++) {
for(let j=1;j<array.length;j++){
for(let k =2;k<array.length;k++){
if(array[i]>array[j] && array[i]>array[k]){
console.log(array[i]);
}
}
}
}
}

It returns 3 100 99.


I want to return just 100 because it is the biggest number.


Is there a better way to use loops to get the biggest value?


Using three different JavaScript loops to achieve this (for, forEach, for of, for in).


You can use three of them to accomplish it.


More From » arrays

 Answers
2

zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:


function biggestNumberInArray (arr) {
// The largest number at first should be the first element or null for empty array
var largest = arr[0] || null;

// Current number, handled by the loop
var number = null;
for (var i = 0; i < arr.length; i++) {
// Update current number
number = arr[i];

// Compares stored largest number with current number, stores the largest one
largest = Math.max(largest, number);
}

return largest;
}

[#52621] Tuesday, February 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breanab

Total Points: 731
Total Questions: 95
Total Answers: 79

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;