Break tie function js
13:18 19 Aug 2015

I'm learning JS and I'm making an app to find the winners per hole in a golf game. The player with less strokes is the winner of the hole, but sometimes more than one player could tie the hole with the same number strokes, so, to find the winner of the hole I need to evaluate the number of strokes from the tied players in the next hole and break the tie, if the tie persist, I need to evaluate the next hole and so on.

The function foo should return an array with the index, position or names from the winner or winners of the hole (if the tie was impossible to break).

Here's my code:

var players = [
    "Jug 1",
    "Jug 2",
    "Jug 3",
    "Jug 4"
];

var arrHoyos = [
    [4, 3, 3, 4],
    [4, 5, 4, 5],
    [4, 4, 5, 6]
];

function foo(array) {
    var arrWinners = [];
    //arrHoyos
    for (var i = 0, len = array.length; i < len; i++) {
        var arr = array[i];
        var arr2 = array[(i + 1) % array.length];
        var pos = 0;
        var min = 0;
        var tie = false;
        var temp = [];
        var temp2 = [];
        min = Math.min.apply(null, arr);
        //arr
        for (var j = 0, len2 = arr.length; j < len2; j++) {
            if (min == arr[j]) {
                temp.push(arr.indexOf(min, j));
            }   
        }
        if (temp.length > 1) {
            tie = true;
            var counter = 0;
            while (tie == true) {
                for (var count = 0; count < temp.length; count++) {
                    pos = temp[count];
                    temp2[count] = arr2[pos];
                }
                min = Math.min.apply(null, temp2);
                for (var count2 = 0; count2 < temp.length; count2++) {
                    if (temp2[count2] != min) {
                        temp.slice(count2, 1);
                    }
                }
                if (temp.length == 1 || counter == array.length) {
                    tie = false;
                }
                counter++;
            }
        }
        arrWinners[i] = players[temp[0]];
        console.log(temp, temp2);
        console.log(arrWinners[i]);
    }
}

foo(arrHoyos);

Chrome console result:

[1, 2] [5, 4]
Jug 2
[0, 2] [4, 5]
Jug 1
[0, 1] [4, 3]
Jug 1
javascript function