Best Way to Get Objects with Highest Property Value

后端 未结 4 1347
故里飘歌
故里飘歌 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:29

    The most straight-forward algorithm to achieve your goal would be:

    1. Find the maximum value for wrong within students array.
    2. Use filter to leave only the relevant students (with the property wrong equals the maximum).

    var students = [{name: "Jack", age: "NYN", attempts: 3, wrong: 2},{name: "Phil", age: "NNNY", attempts: 4, wrong: 3},{name: "Tom", age: "", attempts: 0, wrong: 0},{name: "Lucy", age: "YYNY", attempts: 4, wrong: 1},{name: "Ben", age: "NYNN", attempts: 4, wrong: 3},{name: "Hardest", age: "NNN", attempts: 3, wrong: 3}];
    
    // Find the maximum 'wrong' value
    let maxValue = 0;
    for(let student of students) {
      if(student.wrong > maxValue) {
        maxValue = student.wrong;
      }
    }
    
    // filter out the students with 'wrong' value different than the maximum
    let onlyMax = students.filter(item => item.wrong == maxValue);
    console.log(onlyMax);

    Note all the algorithm does is iterating the array twice, resulting in run-time of O(2n) = O(n).


    The more general solution allows one to find the items with maximum value of property in an objects array:

    var students = [{name: "Jack", age: "NYN", attempts: 3, wrong: 2},{name: "Phil", age: "NNNY", attempts: 4, wrong: 3},{name: "Tom", age: "", attempts: 0, wrong: 0},{name: "Lucy", age: "YYNY", attempts: 4, wrong: 1},{name: "Ben", age: "NYNN", attempts: 4, wrong: 3},{name: "Hardest", age: "NNN", attempts: 3, wrong: 3}];
    
    function filterByMax(arr, property) {
      // Find the maximum 'wrong' value
      let maxValue = 0;
      for(let item of arr) {
        if(item[property] > maxValue) {
          maxValue = item[property];
        }
      }
      
      // filter out the students with 'wrong' value different than the maximum
      return arr.filter(item => item[property] == maxValue);
    }
    
    console.log(filterByMax(students, 'wrong'));

提交回复
热议问题