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

181
Vistas
Calcule el promedio de una matriz con objetos que tiene un objeto anidado

Estoy tratando de recorrer una matriz de Objetos y calcular el promedio de un Objeto anidado que contiene varias claves diferentes. Esta es la matriz de inicio:

 [{ course: "math", id: 4, values: { 2017: 8, 2018: 9 } }, { course: "math", id: 4, values: { 2017: 5, 2019: 7 } }]

Este es mi objetivo:

 {2017:6.5,2018:9,2019:7}

Ahora vuelve correcto para 2017 pero NaN para 2018 y 2019. Si alguien tiene una mejor manera de resolver esto que no requiere tanto, por favor proporcione.

Esto es lo que he intentado hasta ahora. He estado buscando mucho pero realmente no encontré nada que pueda usar.


 const testObject = [{ id: 4, course: "math", values: { 2017: 8, 2018: 9 } }, { id: 5, course: "English", values: { 2017: 8, 2018: 9 } }, { id: 4, course: "math", values: { 2017: 5, 2019: 7 } }, { id: 4, course: "english", values: { 2017: 5, 2019: 7 } }, ] //First I filter out the id 4 and course Math const mathid1 = testObject.filter((e) => e.id === 4 && e.course === "math"); //I than find all the different years const ArrayOfAllYears = [] mathid1.map((element) => { ArrayOfAllYears.push(Object.keys(element.values)); }) //I here find all the different years const withDuplicates = ArrayOfAllYears.reduce(function(arrayOne, arrayTwo) { return arrayOne.concat(arrayTwo); }, []); const withoutDuplicates = Array.from(new Set(withDuplicates)); //Here I just create the calculate average function const Result = {} const calculateAverage = (array) => { const sum = array.reduce((a, b) => a + b); return sum / array.length; }; const newObj = {} withoutDuplicates.map((year) => { let reformattedArray = mathid1.map(obj => { if (obj["values"][year]) { return obj["values"][year] } }) newObj[year] = calculateAverage(reformattedArray) }) console.log(newObj) // I want to calculate the average of the mathid1 values and return it on a Object like {2017:..,2018..}

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

0

Hay dos pasos simples para el problema.

Primero, debe reducir la matriz a un objeto con años y valores:

 // this outputs // { 2017: [8, 5], 2018: [9], 2019: [7] } function byYear(array) { // take each item of an array return array.reduce((acc, data) => { // take the values of that item Object.entries(data.values).forEach(([year, value]) => { // and map all the values to years acc[year] = acc[year] || [] acc[year].push(value) }) return acc }, {}) }

El segundo paso es simplemente tomar promedios:

 function average(object) { const averages = {} for (let key in object) { averages[key] = object[key].reduce((sum, value) => sum + value) / object[key].length } return averages }

Y ahora los juntas:

 average(byYear(input))

Aquí, la input es la matriz filtrada. Como un fragmento completo:

 function byYear(array) { return array.reduce((acc, data) => { Object.entries(data.values).forEach(([year, value]) => { acc[year] = acc[year] || [] acc[year].push(value) }) return acc }, {}) } function average(object) { const averages = {} for (let key in object) { averages[key] = object[key].reduce((sum, value) => sum + value) / object[key].length } return averages } const output = average(byYear([{ course: "math", id: 4, values: { 2017: 8, 2018: 9 } }, { course: "math", id: 4, values: { 2017: 5, 2019: 7 } }])) console.log(output)

about 4 years ago · Juan Pablo Isaza Denunciar

0

El problema con su código actual radica en cómo construye la variable reformattedArray . Primero, observe que su función de mapa devuelve implícitamente undefined cada vez que falta ese año en el objeto actual:

 let reformattedArray = mathid1.map(obj => { if (obj["values"][year]) { return obj["values"][year] } // There is an implicit return undefined, right here... })

Cuando usa el método de matriz .map , cada elemento de la matriz será reemplazado por el valor de retorno de la función de mapa. En el caso de que el año no esté presente, no entrará en el bloque if , por lo que implícitamente devuelve indefinido al llegar al final de la función.

Entonces, en última instancia, todo lo que tiene que hacer es eliminar las entradas undefined de esta matriz y su código funcionará tal como está.


Una forma de hacerlo es simplemente usar .filter(Boolean) en la matriz, que elimina cualquier entrada falsa (que es undefined ). P.ej:

 let reformattedArray = mathid1.map(obj => { /* code here */ }).filter(Boolean); // Note the filter here...

Aquí está su fragmento con esa modificación:

 const testObject = [{ id: 4, course: "math", values: { 2017: 8, 2018: 9 } }, { id: 5, course: "English", values: { 2017: 8, 2018: 9 } }, { id: 4, course: "math", values: { 2017: 5, 2019: 7 } }, { id: 4, course: "english", values: { 2017: 5, 2019: 7 } }, ] //First I filter out the id 4 and course Math const mathid1 = testObject.filter((e) => e.id === 4 && e.course === "math"); //I than find all the different years const ArrayOfAllYears = [] mathid1.map((element) => { ArrayOfAllYears.push(Object.keys(element.values)); }) //I here find all the different years const withDuplicates = ArrayOfAllYears.reduce(function(arrayOne, arrayTwo) { return arrayOne.concat(arrayTwo); }, []); const withoutDuplicates = Array.from(new Set(withDuplicates)); //Here I just create the calculate average function const Result = {} const calculateAverage = (array) => { const sum = array.reduce((a, b) => a + b); return sum / array.length; }; const newObj = {} withoutDuplicates.map((year) => { let reformattedArray = mathid1.map(obj => { if (obj["values"][year]) { return obj["values"][year] } }).filter(Boolean) newObj[year] = calculateAverage(reformattedArray) }) console.log(newObj) // I want to calculate the average of the mathid1 values and return it on a Object like {2017:..,2018..}

about 4 years ago · Juan Pablo Isaza Denunciar

0

  1. Agrupa artículos por año.
  2. Calcular promedio.
 const items=[{ course: "math", id: 4, values: { 2017: 8, 2018: 9 } }, { course: "math", id: 4, values: { 2017: 5, 2019: 7 } }] const groupedValues=items.reduce((groupedValues,item)=>{ Object.entries(item.values).forEach(([year,value])=>{ if(groupedValues[year]){ groupedValues[year]={value:groupedValues[year].value+value,items:groupedValues[year].items+1}; } else { groupedValues[year]={value,items:1}; } }); return groupedValues; },{}) console.log(groupedValues); const result = Object.entries(groupedValues).reduce((result,item)=>{ result[item[0]]=item[1].value/item[1].items; return result; },{}) console.log(result);
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