Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Calcular promedio de marcas en un objeto

He estado luchando con una tarea que he estado haciendo con fines de aprendizaje. Tengo un objeto con algunos estudiantes adentro y quiero calcular las calificaciones promedio de Steven.

Ejemplo:

 const students = [ { name: 'John', surname: 'Johnson', faculty: 'Faculty of Science', modules: [ { title: 'Operating systems', marks: [10, 10, 9] }, { title: 'Algorythms', marks: [8, 10, 8] }, { title: 'Statistics', marks: [9, 7, 8] }, ] }, { name: 'Steven', surname: 'Stevenson', faculty: 'Faculty of Science', modules: [ { title: 'Operating systems', marks: [7, 6, 9] }, { title: 'Algorythms', marks: [7, 8, 9] }, { title: 'Statistics', marks: [6, 8, 10] }, ] }, ];

Usando el método de filtro, pude filtrar solo a Steven del objeto dado.

 const studentSteven = students.filter(student => student.name === 'Steven');

¿Cómo puedo calcular su nota media de todos los módulos? Me gustaría lograr esto usando métodos de matriz. Cualquier consejo sería muy apreciado.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  1. Cree una matriz de marcas con flatMap .

  2. reduce sobre esa matriz para crear un promedio general.

  3. Devuelve un objeto actualizado.

 const students=[{name:"John",surname:"Johnson",faculty:"Faculty of Science",modules:[{title:"Operating systems",marks:[10,10,9]},{title:"Algorythms",marks:[8,10,8]},{title:"Statistics",marks:[9,7,8]}]},{name:"Steven",surname:"Stevenson",faculty:"Faculty of Science",modules:[{title:"Operating systems",marks:[7,6,9]},{title:"Algorythms",marks:[7,8,9]},{title:"Statistics",marks:[6,8,10]}]}]; const out = students.map(obj => { // Destructure the modules property from the // rest of the object properties const { modules, ...rest } = obj; // Return each marks array, and then flatten them const marks = modules.flatMap(obj => obj.marks); // `reduce` over the marks array to create a overall // sum, divide it by the number of marks, // and round up the returned floating-point number const average = Math.round(marks.reduce((acc, c) => { return acc + c; }, 0) / marks.length); // Return a new updated object return { ...rest, average, modules }; }); console.log(out);

Documentación adicional

  • Asignación de desestructuración

  • Resto de sintaxis

  • Difundir sintaxis

about 4 years ago · Juan Pablo Isaza Denunciar

0

const students = [ { name: 'John', surname: 'Johnson', faculty: 'Faculty of Science', modules: [ { title: 'Operating systems', marks: [10, 10, 9] }, { title: 'Algorythms', marks: [8, 10, 8] }, { title: 'Statistics', marks: [9, 7, 8] }, ] }, { name: 'Steven', surname: 'Stevenson', faculty: 'Faculty of Science', modules: [ { title: 'Operating systems', marks: [7, 6, 9] }, { title: 'Algorythms', marks: [7, 8, 9] }, { title: 'Statistics', marks: [6, 8, 10] }, ] }, ]; var studentSteven = students.filter(student => student.name === 'Steven'); studentSteven = studentSteven[0] let g = 0; let sum = 0; for(i = 0;i < studentSteven.modules.length;i++){ sum += studentSteven.modules[i].marks.reduce((s,t)=>{ g++ return s + t }) g++ } avg = sum/g
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede map sobre la matriz de estudiantes y para cada estudiante nuevamente map sobre la matriz de módulos y agregar una propiedad llamada promedio de averageMarks a cada objeto de módulo.

 const students = [ { name: "John", surname: "Johnson", faculty: "Faculty of Science", modules: [ { title: "Operating systems", marks: [10, 10, 9] }, { title: "Algorythms", marks: [8, 10, 8] }, { title: "Statistics", marks: [9, 7, 8] }, ], }, { name: "Steven", surname: "Stevenson", faculty: "Faculty of Science", modules: [ { title: "Operating systems", marks: [7, 6, 9] }, { title: "Algorythms", marks: [7, 8, 9] }, { title: "Statistics", marks: [6, 8, 10] }, ], }, ]; const updatedStudents = students.map((st) => ({ ...st, modules: st.modules.map((mod) => ({ ...mod, averageMarks: mod.marks.reduce((sum, m) => sum + m) / mod.marks.length, })), })); console.log(updatedStudents);

Si también necesita calcular el promedio de todos los módulos, puede encadenar el resultado anterior con otro map y agregar una propiedad average para cada estudiante.

 const students = [ { name: "John", surname: "Johnson", faculty: "Faculty of Science", modules: [ { title: "Operating systems", marks: [10, 10, 9] }, { title: "Algorythms", marks: [8, 10, 8] }, { title: "Statistics", marks: [9, 7, 8] }, ], }, { name: "Steven", surname: "Stevenson", faculty: "Faculty of Science", modules: [ { title: "Operating systems", marks: [7, 6, 9] }, { title: "Algorythms", marks: [7, 8, 9] }, { title: "Statistics", marks: [6, 8, 10] }, ], }, ]; const updatedStudents = students .map((st) => ({ ...st, modules: st.modules.map((mod) => ({ ...mod, averageMarks: mod.marks.reduce((sum, m) => sum + m) / mod.marks.length, })), })) .map((st) => ({ ...st, average: st.modules.reduce((sum, { averageMarks }) => sum + averageMarks, 0) / st.modules.length, })); console.log(updatedStudents);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda