2

My function 'extremeValue' takes 2 parameters, an array and a string "Maximum" or "Minimum", and depending on that string it returns the maximum or minimum value of the array. I used an example array 'values' to pass through the function and while it works out the minimum just fine, the maximum comes out to be the last value of the array. What's wrong with my code?

var values = [4, 3, 6, 12, 1, 3, 7];
            
function extremeValue(array, maxmin) {
	if (maxmin === "Maximum") {
		var max = array[0];
		for (var i = 1; i < array.length; i++) {
			if (array[i] > array[i-1]) {
				max = array[i];
			}
		}
		return max;
	}
	else if (maxmin === "Minimum") {
		var min = array[0];
		for (var j = 1; j < array.length; j++) {
			if (array[j] < array[j-1]) {
				min = array[j];
			}
		}
		return min;
	}
}
            
console.log(extremeValue(values, "Maximum")); 
console.log(extremeValue(values, "Minimum"));

3 Answers 3

4

Change the checking with maximum value.

if (maxmin === "Maximum") {
    var max = array[0];
    for (var i = 1; i < array.length; i++) {
        if (array[i] > max) { //not just before 'array[i-1]'
            max = array[i];
        }
    }
    return max;
}

OR

Simply Use

Math.max.apply( Math, values );

to find Maximum from values.and

Math.min.apply( Math, values );

for minimum values.

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

2 Comments

@jared-smith Thanks for your Edit.
No problem. Good answer.
1

In each loop you must compare an item with maximum (or minimum) value, not before item:

var values = [4, 3, 6, 12, 1, 3, 7];

function extremeValue(array, maxmin) {
    if (maxmin === "Maximum") {
        var max = array[0];
        for (var i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }
    else if (maxmin === "Minimum") {
        var min = array[0];
        for (var j = 1; j < array.length; j++) {
            if (array[j] < min) {
                min = array[j];
            }
        }
        return min;
    }
}

console.log(extremeValue(values, "Maximum")); 
console.log(extremeValue(values, "Minimum"));

Comments

1

Alternatively you can use the Math function to shorten your code:

var values = [4, 3, 6, 12, 1, 3, 7];
            
function extremeValue(array, maxmin) {
	if (maxmin === "Maximum") {
           return Math.max.apply(null, array);
	}
	else if (maxmin === "Minimum") {
	   return Math.min.apply(null, array);
	}
}
console.log(extremeValue(values, "Maximum")); 
console.log(extremeValue(values, "Minimum"));

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.