Rennix
Rennix

Reputation: 49

Math.max method on array with equal values

I'm working on some coderbyte code, and noticed that when I try to get the max item in an array of equal values undefined is returned. When logging the min value is logs 80 and not undefined. Why is this?

Updated Code:

function noRepeat(arr) {
    tmp = []
    if (arr.length === 2 && arr[0] === arr[1]) {
        return arr;
    }
    for (var i = 0;i<arr.length;i++) {
        if (tmp.indexOf(arr[i]) === -1) {
            tmp.push(arr[i])
        }
    }
    return tmp
}
function SecondGreatLow(arr) {
    arr = noRepeat(arr).sort(function (a,b) {return a-b;});
    var low = arr[arr.indexOf(Math.min.apply(Math,arr))+1];
    console.log("low",low);
    var high = arr[arr.indexOf(Math.max.apply(Math,arr))-1];
    console.log("high",high);
    return low +" "+high;
}
console.log(SecondGreatLow([80,80]));

Output:

"low" 80 
"high" undefined
"80 undefined"

Upvotes: 1

Views: 4437

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

That's, actually, ok. How do you want to find the second largest \ smallest number in an array of two similar numbers? It should output "no solution" or something else. Just like there is no solution for an empty array.

function SecondGreatLow(arr) 
{
    arr = noRepeat(arr).sort(function (a,b) {return a-b;});
    if (arr.length < 2)
        return "No solution";
    console.log("low ", arr[1]);
    console.log("high ", arr[arr.length - 2]);
    return low + " " + high;
}

You don't need Math min and max functions as your array is sorted and values are unique. You need to take the second from beginning and the second from the end.

Also, you don't need this part as it is calculated right by algorithm.

if (arr.length === 2) 
{
    return arr[1] + " " + arr[0];
}

For example, you have an array [1, 1, 2].
You remove repetitions and get [1, 2].
Now your algorithms returns low = arr[1] = 2 and high = arr[2 - 2] = arr[0] = 1.
The answer is correct - 2 is the second minimum number and 1 is the second largest.

Upvotes: 1

Related Questions