简体   繁体   中英

How do I add numerical values of a JSON array object?

I am trying to add these integer values from this Array object to get the sum and in turn the average.

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

Output: 9.5

I have been able to do this function, however, I am not able to add the values from the integer into a sum variable and divide by the objectName.length. My sample code is beneath, I want to understand why it is not working?

function my_average_mark(student_grades) {
    sum = 0;
    for( i = 0; i < student_grades.length; i++){
        // console.log(student_grades[i].integer);
        sum += student_grades[i].integer;
        console.log(sum);
        
    }
    
};


all_grades = [
        {"string": "John", "integer": 7},
        {"string": "Margot", "integer": 8},
        {"string": "Jules", "integer": 4},
        {"string": "Marco", "integer": 19}
       ]
console.log(my_average_mark(all_grades));
function my_average_mark(student_grades) {
    sum = 0;
    for( i = 0; i < student_grades.length; i++){
        sum += student_grades[i].integer;        
    }
    return sum / student_grades.length;
};

consider using array functions like map and reduce

function my_average_mark(student_grades) {
    sum = student_grades.map(p => p.integer).reduce((a,b) => a+b, 0)
    return sum / student_grades.length;
};

Your code is almost right, you just need to return the sum divided by the length:

 function my_average_mark(student_grades) { let sum = 0; let len = student_grades.length; for (let i = 0; i < len; i++) { sum += student_grades[i].integer; } return Math.round(sum * 10 / len) / 10; }; all_grades = [ {"string": "John", "integer": 7}, {"string": "Margot", "integer": 8}, {"string": "Jules", "integer": 4}, {"string": "Marco", "integer": 19} ] console.log(my_average_mark(all_grades));

Note you should always declare your variables using var , let or const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM