2

I got trouble using a function within a for loop inside. First look at the code please:

let list1 = [4168,3925,858,2203,440,185,2886,160,1811,4272,4333,2180,174,157,361,1555];

let max = 0;

function maximum(listNumb1) {
	for (let i = 0; i < listNumb1.length; i++) {
		if (listNumb1[i] > max) {
			max = listNumb1[i];
			return max;
		}
	}
}

console.log(maximum(list1));

Ok, I am trying to make function that will find the biggest number in the array above. I made it without a function, and code works, but when I want to make a function, so I can use it with multiple arrays, I am stuck and I am not getting the desired output.

I know where my problem is. It's the return part. Its stopping the code from executing further and I am getting the first number of the array as a output because the for loop stops after the return.

I am asking for solution how should I end, or what should I use instead of return, so I wont break the looping, and the function will continue iterating trough the rest of the numbers in the array, and the max variable will change until it finds the biggest number in the array?

3 Answers 3

2

You need to iterate to the end, because, you do not know if the last element is greater than a found value before.

Move the return value to the end of the function and use a local variable max for keeping a temporary maximum value.

A good idea is to start with the first element of the array as value for max and start the iteration from index 1.

function maximum(array) {
    var max = array[0],
        i;

    for (i = 1; i < array.length; i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max;
}

let list1 = [4168, 3925, 858, 2203, 440, 185, 2886, 160, 1811, 4272, 4333, 2180, 174, 157, 361, 1555];

console.log(maximum(list1));

Sign up to request clarification or add additional context in comments.

Comments

1

It is better to make a function that will return the max file instead of modifying some global var.

You can do something like that:

let list1 = [4168, 3925, 858, 2203, 440, 185, 2886, 160, 1811, 4272, 4333, 2180, 174, 157, 361, 1555];


function findMax(list) {
  return list.reduce((currentMax, currentNumber) => {
    return Math.max(currentNumber, currentMax);
  }, 0);
}

console.log(findMax(list1));

This function uses Array.reduce for seeking for the max value.

1 Comment

You can use Math.max(max, currentNumber); instead of the trinary.
0

Another way to find the maximum is by spreading into Math#max:

const list1 = [4168,3925,858,2203,440,185,2886,160,1811,4272,4333,2180,174,157,361,1555];

const maximum = (arr) => Math.max(...arr);

console.log(maximum(list1));

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.