获得具有最高属性值的对象的最佳方法

时间:2018-06-17 09:47:57

标签: javascript oop

我有以下多维学生对象数组:

for file in list(file_lists):
    filename = os.path.join(path, file)
    df = pd.read_table(filename,sep="|",encoding = "ISO-8859-1")
    df.to_excel(writer, sheet_name=file[:-4], index=False,header=True)
writer.save()

我正在尝试创建一个数组'peopleMostNeedingHelp',它只包含具有最高'错误'属性值的学生。所以'peopleMostNeedingHelp'应该只包含对象Phil,Ben和Hardest。问题是,我做的方式还包括不需要的'杰克',因为他是第一次比较。

如何创建仅返回错误答案最多的人的功能?

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

4 个答案:

答案 0 :(得分:4)

您可以通过检查wrong属性来减少数组。



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 }],
    topWrong = students.reduce((r, o) => {
        if (!r || o.wrong > r[0].wrong) {
            return [o];
        }
        if (o.wrong === r[0].wrong) {
            r.push(o);
        }
        return r;
    }, undefined);
    
console.log(topWrong);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

当发现错误数量较多的新学生时,您必须重置peopleMostNeedingHelp

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

这可以通过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]]);

答案 2 :(得分:1)

如果&#34;错误&#34;您的代码也将失败属性值按升序排列,如

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}
    {name: "Mad", age: "NYN", attempts: 3, wrong: 5},
]

结果将包括Jack,Phil,Ben,Hardest&amp;狂

一旦找到更多&#34;错误&#34;的新人,您必须放弃以前的结果。值,请参阅下面的代码段......

&#13;
&#13;
var s2 = "Jack:NYN,Phil:NNNY,Tom:,Lucy:YYNY,Ben:NYNN,Hardest:NNN";
var s2Arr = s2.split(','); // convert string to an array
var s2MdArr = s2Arr.map(function(e) {return e.split(':'); }); // convert to MD array
var totalWrongAnswers = 0;

for(i=0; i < s2Arr.length; i++) {
    var attempts = s2MdArr[i][1].length;
	var noWrong = (s2MdArr[i][1].match(/N/g) || []).length;
	s2MdArr[i].push(attempts); // add to array[i][2]
	s2MdArr[i].push(noWrong); // add to array[i][3]
	totalWrongAnswers += noWrong; // update total wrong
}

var s2ArrObj = s2MdArr.map(function(e) { return {name: e[0], age: e[1], attempts: e[2], wrong: e[3]} }); // create objects in MD Array

    var firstPerson = s2ArrObj[0]; // initialise so can make a comparison
    var person = firstPerson;
    var peopleMostNeedingHelp = [];
// update person to the person with the highest no. of wrong answers
function something() {
    for (i = 0; i < s2ArrObj.length; i++) {
        // for each person
        if (s2ArrObj[i].wrong > person.wrong) {
            // discard previous results and create new list with single new person only
            person = s2ArrObj[i];
            // update person variable so can compare next person
            peopleMostNeedingHelp = [person];
        }
        else if (s2ArrObj[i].wrong == person.wrong) {
            // add the person to list
            person = s2ArrObj[i];
            // update person variable so can compare next person
            peopleMostNeedingHelp.push(person);
        }
    }
}

something();
console.log(peopleMostNeedingHelp);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

实现目标的最直接的算法是:

  1. wrong数组中找到students的最大值。
  2. 使用filter只留下相关学生(属性wrong等于最大值)。
  3. 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);

    注意所有算法都在迭代数组两次,导致运行时 O(2n)= O(n)

    更通用的解决方案允许人们在对象数组中找到最大值为property的项目:

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