Best Way to Get Objects with Highest Property Value

后端 未结 4 1349
故里飘歌
故里飘歌 2021-01-28 01:54

I have the following multidimensional array of student objects:

var students = [
{name: \"Jack\", age: \"NYN\", attempts: 3, wrong: 2},
{name: \"Phil\", age: \"N         


        
4条回答
  •  旧巷少年郎
    2021-01-28 02:35

    You have to reset the peopleMostNeedingHelp when a new student with a higher number of errors is discovered:

    let mostNeedingHelp = [students[0]];
    
    for(const student of students.slice(1)) {
      if(student.errors === mostNeedingHelp[0].errors) {
        mostNeedingHelp.push(student);
      } else if(student.errors >= mostNeedingHelp[0].errors) {
        mostNeedingHelp = [student]; // <<<<
      }
    }
    

    This can be shortified with reduce:

    const mostNeedingHelp = students.slice(1).reduce((arr, student) => 
     arr[0].errors === student.errors ? arr.concat(student) : arr[0].errors < student.errors ? [student] : arr, [students[0]]);
    

提交回复
热议问题