B R B R - 9 months ago 37
Javascript Question

Sum multiple objects in multiple arrays and then average sums

I have a object with the name, race number` (1,2,3) and finishing position of multiple drivers. I want to iterate through each array and display (console.log is fine) the race number, finishing position and then average finishing position for each driver.

Below is the data and desired output:

{
"drivers":[
{
"Name":"Smith",
"races": [
{
"race 1":"12"
},
{
"race 2":"6"
},
{
"race 3":"10"
}
]
},
{
"Name":"Jones",
"races": [
{
"race 1":"11"
},
{
"race 2":"6"
},
{
"race 3":"5"
}
]
}
]
}


Output:

Smith:
Race 1 finishing position: 12
Race 2 finishing position: 6
Race 3 finishing position: 10
Average finishing position: 9.3

Jones:
Race 1 finishing position: 11
Race 2 finishing position: 6
Race 3 finishing position: 5
Average finishing position: 7.3

Answer Source

I just loop it and to get the race no use Object.keys()

 var data = {
        "drivers":[
        {
            "Name":"Smith",
                "races": [
                {
                    "race 1":"12"
                },
                {
                    "race 2":"6"
                },
                {
                    "race 3":"10"
                }
            ]
        },
        {
            "Name":"Jones",
                "races": [
                {
                    "race 1":"11"
                },
                {
                    "race 2":"6"
                },
                {
                    "race 3":"5"
                }
                ]
            }
        ]
    };


    for(var x in data.drivers) {
        console.log(data.drivers[x].Name + ":");
        var total = 0;
        for(var i in data.drivers[x].races) {
            var key = Object.keys(data.drivers[x].races[i]);
            total += parseInt(data.drivers[x].races[i][key]);
            console.log(key+ " finishing: "+data.drivers[x].races[i][key]);
        }
        console.log('Average finishing position: ' + (total/3).toFixed(1));
    }