Home > Enterprise >  how do I add array in object property in another array as parameter in function?
how do I add array in object property in another array as parameter in function?

Time:12-03

i tried to make a function for averaging all the array in an object of another array, but however i tried i can't call the parameter for the function i make

let students = [randy, riziq, rama];
let randy = {
  name: 'Randy',
  score: [75, 80, 90]
};
let riziq = {
    name: 'Riziq',
    score: [50, 90, 90]
};
let rama = {
    name: 'Rama',
    score: [80, 75, 90]
};

function average(/*students*/) {
    let avgScore = /*students's score avg*/ 
return /*students's name   ""   student's average*/ 
};

console.log(average(/*students*/));

is there any way to call that?

i tried to make a for loop to each of the props inside the students array but still i can't call that. i tried to sum all the student's score with array.reduce() of the students array and divide them with array.length

CodePudding user response:

Put let students = [randy, riziq, rama]; after the declaration of variables.

let randy = {
  name: 'Randy',
  score: [75, 80, 90]
};
let riziq = {
    name: 'Riziq',
    score: [50, 90, 90]
};
let rama = {
    name: 'Rama',
    score: [80, 75, 90]
};

let students = [randy, riziq, rama];

function average(students) {
    return students.map(({name, score}) => {
    const total = score.reduce((a, b) => a   b,0);
    return `${name} ${total/score.length}`;
});
}

console.log(average(students));

Learn more about .map() and .reduce()

CodePudding user response:

let randy = {
             name: 'Randy',
             score: [75, 80, 90]
            };
let riziq = {
             name: 'Riziq',
             score: [50, 90, 90]
            };
let rama =  {
             name: 'Rama',
             score: [80, 75, 90]
            };
            let students = [randy, riziq, rama];
            
function average(students) {
    var data = { "averages" : {}};
    var i;
    for (i = 0; i < students.length;   i) {
        var total = 0;
        for (var ti = 0; ti < students[i].score.length; ti  ) {
            total  = students[i].score[ti] << 0;
        }
        var avg = total/students[i].score.length;
                    
        data.averages[i] = { 
                            "name":students[i].name,  
                            "average":avg.toFixed(2),  
                           }; 
     }
                
     return data;
};
            
console.log(average(students));

  • Related