Kovacs Akos Kovacs Akos - 5 months ago 14
Javascript Question

Highest value of an array

I have an array, which contains several numbers, like this:

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")


I would like to get smallest and greatest number from this array. It seems pretty easy task, but accidently I get wrong output for code below.

function highAndLow(numbers){
var args = Array.prototype.slice.call(arguments);
var m = 0, i = 0, n = args.length;

console.log(args.length)

for (i=0; i < n; i++) {
if (args[i] > m) {
m = args[i];
console.log(m)
}
}

return m

}


It says length is 1 and return value is 0.

Answer

You have a string as parameter. You need to split first. And convert to Number.

args = numbers.split(' ').map(Number);

A minor hint: You can use the first element as first min/max value and iterate from the second element.

function highAndLow(numbers) {
    var args = numbers.split(' ').map(Number),
        min = args[0],
        max = args[0],
        i = 0,
        n = args.length;

    for (i = 1; i < n; i++) {
        if (args[i] < min) {
            min = args[i];
        }
        if (args[i] > max) {
            max = args[i];
        }
    }
    return { min: min, max: max };
}

console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));