【问题标题】:Average of array inside an object对象内数组的平均值
【发布时间】:2020-10-12 13:13:34
【问题描述】:

我有一个包含学生姓名和分数的对象数组。如下所示

我需要计算每个学生的“平均”分数,并比较“平均”分数以获得最优秀的学生。我正在尝试如下,我没有得到我缺少的东西?

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)

我需要每个学生的平均分来比较所有学生的结果

【问题讨论】:

    标签: javascript arrays object average


    【解决方案1】:

    也许是这样的:

    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);

    【讨论】:

      【解决方案2】:

      我们开始吧。它会返回一个包含学生姓名和平均分数的对象数组。

      它也是从最高平均到最低排序

      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);

      【讨论】:

        【解决方案3】:

        如果您正在寻找传统循环:

        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)
        

        【讨论】:

        • 嗨,谢谢。我想用传统的方式。我怎样才能 console.log 例如“Alin 的平均水平......而 Bob 的平均水平......”就像打印每个学生的平均数字一样?
        • @Sal 你只需要在循环内打印,或者附加到变量像var msg = Students[i]["name"] + " has average mark: " + average;
        • @Sal 我已经更新了我的答案,你可以看到我是如何把它印在罐子里的
        • 您好 Doston,感谢您抽出宝贵时间。我想将平均数添加到对象中,使其变为 [{name:"Bob", average : 89}, {name:"alin", average : 87}],并对数组进行排序以便我可以拥有谁得到最高的平均数。如果 Alin 和 Bob 都得到相同的数字,我也需要比较一下。你能进一步指导我吗?
        • @Sal 感谢您的接受,我已经发布了您第二个问题的答案:stackoverflow.com/a/64321145/7186690 如果您有任何问题,请告诉我
        【解决方案4】:

        您需要reduce 每个Studentmarks 数组,而不是Student 对象,因为这不是数组。

        next 是数组中的下一个值,而不是Students 中的下一项。

        最后,将console.log 行放在循环内,以便打印出所有结果。

        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);
        }

        【讨论】:

          【解决方案5】:

          你也可以在函数中提取它:

          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;
          }

          【讨论】:

            【解决方案6】:

            以下是使用Array.reduceArray.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;
            }

            注意:在上面的示例中,我没有考虑是否有多个学生具有相同的平均值。

            下面是一个例子,如果平均值相同,将返回所有学生

            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;
            }

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-04-05
              • 1970-01-01
              • 1970-01-01
              • 2021-02-07
              • 1970-01-01
              • 1970-01-01
              • 2021-08-28
              • 2014-05-10
              相关资源
              最近更新 更多