Media dell'array all'interno di un oggetto
Ho una serie di oggetti che contengono il nome e i voti degli studenti. come sotto
Devo calcolare i voti "medi" di ogni studente e confrontare i voti "medi" per ottenere lo studente migliore. Sto provando come di seguito, non ottengo cosa mi manca?
var Students = [
{
name: "Bob",
marks: [78,80,89,90,68]
},
{
name: "Alin",
marks: [87,60,59,70,68]
},
{
name: "bikash",
marks: [82,60,79,60,80]
}
];
for (let i = 0; i < Students.length; i++){
var average = Students[i].reduce((total, next)=> total + next.marks) /2
}
console.log(average)
Devo avere voti medi di ogni studente per confrontare i risultati di Tutti gli studenti
Risposte
Se stai cercando un loop tradizionale:
const Students = [{
name: 'Bob',
marks: [78, 80, 89, 90, 68],
},
{
name: 'Alin',
marks: [87, 60, 59, 70, 68],
},
{
name: 'bikash',
marks: [82, 60, 79, 60, 80],
},
];
var average;
for (let i = 0; i < Students.length; i++){
var marks = Students[i]["marks"];
var total = 0;
console.log(marks);
for (var j = 0; j < marks.length; j++ ) {
total += marks[j];
}
average = total / marks.length;
// answer for question in the comment
var msg = Students[i]["name"] + " has average mark: " + average;
console.log(msg)
}
console.log(average)
Forse questo:
const students = [{
name: 'Bob',
marks: [78, 80, 89, 90, 68],
},
{
name: 'Alin',
marks: [87, 60, 59, 70, 68],
},
{
name: 'bikash',
marks: [82, 60, 79, 60, 80],
},
];
const topStudent = students
.map(student => ({
...student,
averageMark: student.marks.reduce((a, b) => a + b, 0) / student.marks.length,
}))
.sort((a, b) => a.averageMark - b.averageMark)
.pop();
console.log(topStudent);
Eccoci qui. Ti restituisce una serie di oggetti con il nome e il punteggio medio degli studenti.
È anche ordinato dalla media più alta alla più bassa
let arr = [
{
name: "Bob",
marks: [78,80,89,90,68]
},
{
name: "Alin",
marks: [87,60,59,70,68]
},
{
name: "bikash",
marks: [82,60,79,60,80]
}
]
let averages = arr.map(({ marks, name }) => {
let average = marks.reduce((a,v) => a + v) / marks.length
return { name , average }
}).sort((a,b) => b.average - a.average);
let [{ name }] = averages;
console.log(averages)
console.log("top student: ", name);
È necessario reducel' marksarray di ciascuno Student, non un Studentoggetto, poiché questo non è un array.
nextè il valore successivo nella matrice, non l'elemento successivo in Students.
Infine, posiziona la console.loglinea all'interno del ciclo in modo da stampare tutti i risultati.
var Students = [
{
name: "Bob",
marks: [78,80,89,90,68]
},
{
name: "Alin",
marks: [87,60,59,70,68]
},
{
name: "bikash",
marks: [82,60,79,60,80]
}
];
for (let i = 0; i < Students.length; i++){
var average = Students[i].marks.reduce((total, next)=> total + next) / Students[i].marks.length;
console.log(average);
}
Puoi anche estrarlo in una funzione:
var Students = [
{
name: "Bob",
marks: [78,80,89,90,68]
},
{
name: "Alin",
marks: [87,60,59,70,68]
},
{
name: "bikash",
marks: [82,60,79,60,80]
}
];
// Student avarage
var averages = []
for (let i = 0; i < Students.length; i++){
var avg = average(Students[i].marks);
console.log(Students[i].name + ": " + avg)
averages.push(avg)
}
// Total average
console.log("total average: " + average(averages))
function average(array) {
return array.reduce((total, mark) => total + mark, 0) / array.length;
}
Qui di seguito è uno dei modi di trovare lo studente con la massima media utilizzando Array.reduce, Array.map.
var Students = [{name:"Alin",marks:[87,60,59,70,68]},{name:"Bob",marks:[78,80,89,90,68]},{name:"bikash",marks:[82,60,79,60,80]}];
const getTopStudent = (students) => {
//Find the avg of the current student
const formattedStudents = students.map(student => ({...student, avg: student.marks.reduce((t, m) => t+m, 0)/student.marks.length}))
return formattedStudents.reduce((res, student) => {
//Check if the avg of the student in res object is less than the avg of the current student, then return current student.
if((res.avg || 0) < student.avg){
return {
...student
}
}
return res;
}, {})
}
console.log(getTopStudent(Students))
.as-console-wrapper {
max-height: 100% !important;
}
Nota: Nell'esempio sopra non ho considerato se ci sono più di uno studente con la stessa media.
Di seguito è riportato l'esempio che restituirà tutti gli studenti se la media è la stessa
var Students = [{name:"Alin",marks:[87,60,59,70,68]},{name:"Bob",marks:[78,80,89,90,68]},{name:"bikash",marks:[82,60,79,60,80]},{name:"Joey",marks:[78,80,84,90,73]}];
const getTopStudent = (students) => {
const formattedStudents = students.map(student => ({ ...student,
avg: student.marks.reduce((t, m) => t + m, 0) / student.marks.length
}))
const finalRes = formattedStudents.reduce((res, student) => {
//if the res.avg is less than current student avg then update the res object with the new avg and the students
if ((res.avg || 0) < student.avg) {
return {
avg: student.avg,
students: [{ ...student }]
}
} else if ((res.avg || 0) === student.avg) {
//If average of the current student is same as res.avg, then push the current student to the res.students
res.students.push(student);
return res;
}
return res;
}, {});
return finalRes.students;
}
//More than one student with max avg
console.log(getTopStudent(Students));
//One student with max avg
console.log(getTopStudent(Students.slice(0,3)));
.as-console-wrapper {
max-height: 100% !important;
}