Best Way to Get Objects with Highest Property Value

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

    You could reduce the array by checking the wrong 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 }],
        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; }

提交回复
热议问题