1

I am trying to pull the largest number of an array using a forEach Javascript method. This is what I have so far, but I know it's not correct.

var arr = [2,3,4];
var largest = 0;
 
arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
  console.log(largest);
});

0

6 Answers 6

6

This will work

var arr = [2,3,4];
var largest = 0;

arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
});

console.log(largest);

but why would you even do that? Why not use Math max?

var largest = Math.max.apply(Math, arr);
Sign up to request clarification or add additional context in comments.

Comments

2

To cover negative numbers in array, it is safe to assign largest to be the first element in array.

var arr = [2,3,4];
var largest = arr[0];
 
arr.forEach(function(elem){
  if(largest < elem) 
  largest = elem;
});
console.log(largest);

Comments

2

You can simply use spread operator:

var arr = [2,3,4];
var largest = Math.max(...arr); 
console.log(largest);

Comments

1

If you put console.log(largest); outside forEach loop, it will print the largest number in the array.

Comments

1
var
    a = [2,3,4,2,1,9],
    largest = 0;

a.forEach(function(value){
    console.log('current array element value: ' + value + '.  Is it larger than the largest?', (largest > value));
    if (largest < value) largest = value;
    console.log('largest value now is: ', largest);
});
console.log('largest is changed here, because it was not redefined inside the function of the forEach method: ', largest, '.\n But it was defined within its context.');

Comments

0
function greatest(array) {
    if(array == undefined){
        console.log('There are no elements in array.');
    }

    const max = array.reduce(function(first, next){
        return first > next ? first : next; 
    });

    console.log(`Maximum element is ${max}`);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.