Javascript获取按另一个属性分组的最大值



你好,我有一个数组,看起来像这个

result.entities= [
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "50"},
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "2"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "33"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
]

我想获得每个";zs_ numero";然后将所有的最大分数与系数相乘得到最终结果所以我想得到这样的值:

newarray= [
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
]

然后制作一个变量来计算所有(zs_coefficiency*zs_score),并将它们加在一起

我试过了,但不起作用

var newarray = []
result.entities.forEach(function (a) {
if (!this[a.zs_numero]) {
this[a.zs_numero] = { zs_numero: a.zs_numero, zs_coefficient: 0, zs_score: 0 };
newarray.push(this[a.zs_numero]);
}
this[a.zs_numero].zs_coefficient = a.zs_coefficient;
this[a.zs_numero].zs_score = Math.max(this[a.zs_numero].zs_score, a.zs_score);
}, Object.create(null));
console.log(newarray)
for(var i = 0; i < newarray.length; i++){
max=max+newarray.zs_coefficient*newarray.zs_score
}

您可以使用Array.reduce()来获得所需的结果,创建一个基于zs_numero的映射。如果zs_numero属性中不存在对象,则zs_score大于现有值,我们将替换它。

我们可以再次使用Array.reduce()来计算总和(zs_coefficient x zs_score的总和);

result = { 
entities: [
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "50"},
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "2"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "33"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
]
}
const output = Object.values(result.entities.reduce ((acc, cur) => { 
if (!acc[cur.zs_numero] || (+cur.zs_score > +acc[cur.zs_numero].zs_score)) {
acc[cur.zs_numero] = cur;
}
return acc;
}, {}));
console.log('Output:', output)
const total = output.reduce((acc, cur) => { 
return acc + cur.zs_score * cur.zs_coefficient
}, 0);
console.log('Total score:', total);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这里有一个简单的循环来解决您的问题。

const entities= [
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "50"},
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "2"},
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "33"},
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
]
let finalResult = []
entities.map(d => {
let index = finalResult.findIndex(p => p.zs_numero == d.zs_numero)
if(index == -1) {
finalResult.push(d)
} else {
if(parseInt(d.zs_score) > parseInt(finalResult[index].zs_score)) {
finalResult[index] = {...d};
}
}
})
console.log(finalResult)
let Total = 0;
finalResult.map(d=> {Total += (d.zs_score * d.zs_coefficient)})
console.log(Total)

相关内容

  • 没有找到相关文章

最新更新