خرید بک لینک

Vote count: 0

So, I was working on this challenge to retu the third largest number in an array. I had got it worked out until I realized that I must account for repeat numbers. I handled this by adding 3 layers of for loops with variables i, j, and k. You'll see what I mean in the code. This is not terribly efficient or scalable. My question is, how can I optimize this code? What other methods should I be using?

function thirdGreatest (arr) {
    arr.sort(function(a, b) {
        if (a < b) {
            retu 1;
        } else if (a > b) {
            retu -1;
        } else {
            retu 0;
        }
    });

    for ( var i = 0; i < arr.length; i++) {
        for (var j = 1; j < arr.length; j++) {
            for (var k = 2; k < arr.length; k++) {
                if (arr[i] > arr[j]) {
                    if (arr[j] > arr[k]) {
                        retu arr[k];
                    }

                }
            }
        }
    }


}

console.log(thirdGreatest([5, 3, 23, 7,3,2,5,10,24,2,31, 31, 31])); // 23
console.log(thirdGreatest([5, 3, 23, 7,3,2,5,10,24,2,31])) // 23
console.log(thirdGreatest([5, 3, 7, 4])); // 4
console.log(thirdGreatest([2, 3, 7, 4])); // 3

asked 3 mins ago

برچسب: نویسنده: استخدام کار تاريخ: چهارشنبه 29 ارديبهشت 1395 ساعت: 8:13

صفحه بندی