Search code examples
javascriptarrayshashmaphashtableaverage

Return an average from an array of hash


I am new to working with hashes in javascript and would like to write a function that takes an array of hash and returns the average "grade" for a class.

Here is an example:

Input:

    {"string": "John", "integer": 7},
    {"string": "Margot", "integer": 8},
    {"string": "Jules", "integer": 4},
    {"string": "Marco", "integer": 19}
   

Output: 9.5

Thanks in advance!


Solution

  • let items = [
        {"string": "John", "integer": 7},
        {"string": "Margot", "integer": 8},
        {"string": "Jules", "integer": 4},
        {"string": "Marco", "integer": 19}
    ]
    
    let avg = items.reduce((a, b) => a + b.integer, 0) / items.length
    
    console.log(avg)