Hello I have an array that looks like this
JavaScript
x
9
1
result.entities= [
2
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "50"},
3
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
4
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "2"},
5
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
6
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "33"},
7
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
8
]
9
I wanted to get the maximum score for each “zs_numero” and then multiply all the maximum scores with the coefficient to get a final result So i want to get the values like this:
JavaScript
1
6
1
newarray= [
2
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
3
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
4
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
5
]
6
and then make a a variable that calculate all the (zs_coefficient*zs_score) and add them together
I tried this but it didnt work
JavaScript
1
15
15
1
var newarray = []
2
result.entities.forEach(function (a) {
3
if (!this[a.zs_numero]) {
4
this[a.zs_numero] = { zs_numero: a.zs_numero, zs_coefficient: 0, zs_score: 0 };
5
newarray.push(this[a.zs_numero]);
6
}
7
this[a.zs_numero].zs_coefficient = a.zs_coefficient;
8
this[a.zs_numero].zs_score = Math.max(this[a.zs_numero].zs_score, a.zs_score);
9
}, Object.create(null));
10
console.log(newarray)
11
12
for(var i = 0; i < newarray.length; i++){
13
max=max+newarray.zs_coefficient*newarray.zs_score
14
}
15
Advertisement
Answer
You can use Array.reduce()
to get the desired result, creating a map keyed on zs_numero
. If there is no object present at the zs_numero property or the zs_score is greater than the existing value, we replace it.
We can use Array.reduce()
again to calculate the total (sum of zs_coefficient x zs_score);
JavaScript
1
24
24
1
result = {
2
entities: [
3
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "50"},
4
{zs_numero: "1", "zs_coefficient": "2", "zs_score": "55"},
5
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "2"},
6
{zs_numero: "2", "zs_coefficient": "4", "zs_score": "10"},
7
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "33"},
8
{zs_numero: "3", "zs_coefficient": "3", "zs_score": "35"},
9
]
10
}
11
12
const output = Object.values(result.entities.reduce ((acc, cur) => {
13
if (!acc[cur.zs_numero] || (+cur.zs_score > +acc[cur.zs_numero].zs_score)) {
14
acc[cur.zs_numero] = cur;
15
}
16
return acc;
17
}, {}));
18
19
console.log('Output:', output)
20
21
const total = output.reduce((acc, cur) => {
22
return acc + cur.zs_score * cur.zs_coefficient
23
}, 0);
24
console.log('Total score:', total);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }