javascript - 按 id 过滤对象并找到最高分

标签 javascript arrays json vue.js javascript-objects

我正在尝试找到按 id 对对象进行排序的正确语法,然后找到该 id 数组的最高分。到目前为止,我已经使用条件和 sort() 方法对对象进行了排序,但我想通过 Lesson_id 将对象压缩到最高分。我错过了什么?

到目前为止我得到的是:

    34: {user: 6, lesson_id: 2, score: 50, complete: true}
    35: {user: 6, lesson_id: 1, score: 50, complete: true}
    36: {user: 6, lesson_id: 2, score: 50, complete: true}
    38: {user: 6, lesson_id: 2, score: 100, complete: true}
    39: {user: 6, lesson_id: 2, score: 100, complete: true}
    40: {user: 6, lesson_id: 2, score: 100, complete: true} 

但我想要这样的:

    0: {user: 6, lesson_id: 2, score: 100, complete: true}
    1: {user: 6, lesson_id: 1, score: 50, complete: true}

这是我到目前为止所得到的(Vue3.js):

    mounted() {
      this.quizArray = response.data;
      const arrayFilter = this.quizArray;
      const user_id = this.user_profile[0]["id"];
      var newObj = [];
      var listSort = function () {
        for (var i = 0; i < arrayFilter.length; i++) {
          if (arrayFilter[i].student["id"] === user_id) {
            if (arrayFilter[i].score !== null) {
              if (arrayFilter[i].complete === true) {
                arrayFilter.sort((a, b) => a.score - b.score);
                //not sure about this part ....
                newObj[i] = {
                  user: arrayFilter[i].student["id"],
                  lesson_id: arrayFilter[i].quiz["lesson_id"],
                  score: arrayFilter[i].score,
                  complete: arrayFilter[i].complete
                }
              }
            }
          }
        }
      };
      newObj = this.filteredResults; 
            console.log(this.filteredResults)
      listSort();
      
      // const highest = this.filteredResults.sort((a, b) => b.score - a.score)[0]
      // console.log(highest) works but only for one lesson
     });
    },

这是原始对象:

35:
complete: true
quiz: {id: 1, lesson_id: 1, question: 'What is heat transfer?', answer: 'Its is a type of blah', op1: 'Its balahsdd', …}
score: 50
student: {user: 'Mark', name: 'Mark', occupation: 'Commissioning Technician', residence: 'Australia', active_id: false, …}

最佳答案

我建议使用 JS 方法来实现这一点,它会清理代码。另外,我不认为对数组进行排序有什么意义,如果您只需要最高值,可以使用下面的代码片段。 @编辑我忘记了每节课的分组,更新了下面的答案

const userId = this.user_profile[0]["id"];

// get all completed quiz elements for student and with score different than null
const quizForStudent = this.quizArray.filter(quiz => quiz.student.id === userId && quiz.complete && quiz.score !== null)

// find highest value for all lessons
// const highest = quizForStudent.reduce((prev, current) => prev.score > current.score ? prev : current)

// group elements per lesson id. this will give result in format
// {
//     2: [{complete: true, quiz: {lesson_id: 2, ...}, score: 100, student: {...}, {complete: true, quiz: {lesson_id: 2, ...}, score: 100, student: {...}, ...]
//     1: [{complete: true, quiz: {lesson_id: 1, ...}, score: 100, student: {...}]
// }
const scorePerLesson = quizForStudent.reduce((object, current) => {
    // make sure array exist for given lessonId
    object[current.quiz.lesson_id] = object[current.quiz.lesson_id] || []
    // add array to object
    object[current.quiz.lesson_id].push(current)

    return object
},{})

// find highest score for each lesson
// {
//     2: {complete: true, quiz: {lesson_id: 2, ...}, score: 100, student: {...}
//     1: {complete: true, quiz: {lesson_id: 1, ...}, score: 100, student: {...}
// }
const highestScorePerLesson = Object.entries(scorePerLesson).reduce((object, [lessonId, quiz]) => ({
    ...object,
    [lessonId]: quiz.reduce((prev, current) => prev.score > current.score ? prev : current)
}), {})

要获得给定类(class)(例如第 2 课)的最高分,您可以使用

highestScore[2]

在沙箱中 checkout :link

关于javascript - 按 id 过滤对象并找到最高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71421527/

相关文章:

javascript - 将canvas中的文字绘制成三个js作为sprite

php - 无法访问通过 PHP 中的 Post 方法发布的数组的值

ruby-on-rails - 如何在 Carrierwave 中为图像 [0] 设置默认 url?

javascript - 公用电脑如何防止JS劫持

javascript - 功能组件是否在底层变成了类组件?

javascript - 如何在node.js上实现jQuery直接上传到Cloudinary

java - 在 Java 中检查两个数组是否相等时出现意外结果

c++ - 即使我可以访问单个元素,也不在 C++ 中的字符串类数组中打印任何内容

jquery - 如何使用 jQuery 从 json 对象中获取一些值?

java - 通过 Jackson ObjectMapper 将参数化 url 反序列化为 java.net.URI 时出现 InvalidFormatException