Best Way to Get Objects with Highest Property Value

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

    Your code will also fail if the "wrong" property values are in ascending order like

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

    The result will include Jack, Phil, Ben, Hardest & Mad


    You have to discard the previous results once you find new person with greater "wrong" value, see the snippet below...

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

提交回复
热议问题