Javascript-从数组返回最大数

时间:2018-12-17 19:42:52

标签: javascript

我有一个包含对象的数组。像这样:

var arr = [{name: "Matt",age: 24 ,grades: [100,100,100,100]}

在我的代码中,我有5个类似的对象,它们的名称/年龄/等级都是随机的。我想返回平均成绩最高的对象。 这是我的代码:

var grades = [];
    var arr = [{
        name: "John",
        age: 24,
        grades: [100,100,100,100]
    }, {
        name: "Brock",
        age: 23,
        grades: [55,65,75,85]
    }, {
        name: "Matt",
        age: 24,
        grades: [88,78,65,95]
    }, {
        name: "Jay",
        age: 28,
        grades: [32,85,99,99]
    }, {
        name: "Monica",
        age: 25,
        grades: [45,63,82,81]
    }];

function avg(x) {
    var num = 0;
    for (var i=0; i<x.length; i++) {
        num += x[i]
    }
    return num / x.length;
}


//Go over the whole array
for (var i=0; i<arr.length; i++) {
    for (var x=0; x<arr[i].grades.length; x++) {
        var a = avg(arr[i].grades);
        /////// What to do next? ^ returns all averages

    }
}




console.log(arr);

就是这样。我只想返回console.log,获得平均成绩最高的对象。有人可以帮我吗?或至少给我一个主意

1 个答案:

答案 0 :(得分:2)

不需要内部循环。

var arr = [{ name: "John", age: 24, grades: [100,100,100,100] }, { name: "Brock", age: 23, grades: [55,65,75,85] }, { name: "Matt", age: 24, grades: [88,78,65,95] }, { name: "Jay", age: 28, grades: [32,85,99,99] }, { name: "Monica", age: 25, grades: [45,63,82,81] }];

function avg(x) {
    var num = 0;
    for (var i=0; i<x.length; i++) {
        num += x[i]
    }
    return num / x.length;
}

let maxAvg = 0;
let maxAvgObj = null;
for (var i=0; i<arr.length; i++) {
    var a = avg(arr[i].grades);
    if (a > maxAvg) {
        maxAvg = a;
        maxAvgObj = arr[i];
    }
}

console.log(maxAvg, maxAvgObj)

可以进一步简化逻辑:

const arr = [{ name: "John", age: 24, grades: [100,100,100,100] }, { name: "Brock", age: 23, grades: [55,65,75,85] }, { name: "Matt", age: 24, grades: [88,78,65,95] }, { name: "Jay", age: 28, grades: [32,85,99,99] }, { name: "Monica", age: 25, grades: [45,63,82,81] }];

const [maxAvg, maxAvgObj] = arr.reduce(([currMaxAvg, currMaxAvgObj], obj) => {
    const avg = obj.grades.reduce((sum, grade) => sum + grade, 0) / obj.grades.length;
    return avg > currMaxAvg ? [avg, obj] : [currMaxAvg, currMaxAvgObj];
}, [[]]);

console.log(maxAvg, maxAvgObj)