如何计算阵列的平均评分?

时间:2020-10-25 08:14:40

标签: javascript arrays average

下面给出了一个数组数据:

    const ratingData = [
        {name: 'St. Marys School', rating:5},
        {name: 'St. Zaviers School', rating:4},
        {name: 'St. Marys School', rating:3},
        {name: 'Rahul English Medium School', rating:2},
        {name: 'St. Francis High School', rating:3},
        {name: 'Rahul English Medium School', rating:1},
        {name: 'St. Francis High School', rating:4},
        {name: 'Mother Marys High School', rating:5}
    ];

在此数组中,我想计算每个学校数据的平均评分。但是问题是重复的条目,例如“圣玛丽学校”有2个条目具有不同的评分。如何合并为一个并计算其平均评分?我尝试使用map函数,但是对于每个条目,它都无法正常工作。

o / p应该看起来像这样。 (这只是一个例子)

const output = [
     { name: 'St. Marys School', averageRating: 4},
     { name: 'St. Zaviers School', averageRating: 4},
     { name: 'Rahul English Medium School', averageRating: 1.5},
     { name: 'St. Francis High School', averageRating: 3.5},
     { name: 'Mother Marys High School', averageRating: 5}
];

2 个答案:

答案 0 :(得分:0)

以下是将distreduce()结合使用以检测重复条目的示例。

首先,它将原始数组缩小为Map,该数组会累积数组中重复条目的评分。

Map

然后我们使用{ {'St. Marys School': [5, 3, 1]}, {'St. Zaviers School': [4]}, ... } 将此Map转换回数组,并将评分数组减少为平均值。

Array.from

答案 1 :(得分:0)

let ratingData = [
    {name: 'St. Marys School', rating:5},
    {name: 'St. Zaviers School', rating:4},
    {name: 'St. Marys School', rating:3},
    {name: 'Rahul English Medium School', rating:2},
    {name: 'St. Francis High School', rating:3},
    {name: 'Rahul English Medium School', rating:1},
    {name: 'St. Francis High School', rating:4},
    {name: 'Mother Marys High School', rating:5}
];

let sumData = {};

for (let element of ratingData) {
    if (sumData[element.name]) {
        sumData[element.name].sum = sumData[element.name].sum + element.rating;
        sumData[element.name].n++;
    } else {
        sumData[element.name] = {
            sum: element.rating,
            n: 1
        };
    }
}

console.log('sumData: ' + JSON.stringify(sumData));

let averageData = [];

for (let element of Object.keys(sumData)) {
    averageData.push({
        name: element,
        rating: sumData[element].sum / sumData[element].n
    });
}

console.log('averageData: ' + JSON.stringify(averageData));

sumData将等于

{
    "St. Marys School": {
        "sum": 8,
        "n": 2
    },
    "St. Zaviers School": {
        "sum": 4,
        "n": 1
    },
    "Rahul English Medium School": {
        "sum": 3,
        "n": 2
    },
    "St. Francis High School": {
        "sum": 7,
        "n": 2
    },
    "Mother Marys High School": {
        "sum": 5,
        "n": 1
    }
}

平均数据等于

[
    {
        "name": "St. Marys School",
        "rating": 4
    },
    {
        "name": "St. Zaviers School",
        "rating": 4
    },
    {
        "name": "Rahul English Medium School",
        "rating": 1.5
    },
    {
        "name": "St. Francis High School",
        "rating": 3.5
    },
    {
        "name": "Mother Marys High School",
        "rating": 5
    }
]