I need to calculate average
and max
rating.
From my perspective this should use map
and reduce
for this purpose, but, I'm not sure if the JSON has the right format, or if it needs any sanitization.
const
myJSON =
[ { "page": 1, "totalPages": 2, "data":
[ { "title": "Developer 1", "rating": 4.7}
, { "title": "Developer 2", "rating": 7.8}
] } ]
;
var Max_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating > cur.rating)? acc : cur) );
var Min_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating < cur.rating)? acc : cur) );
var Avg_JSO = myJSON.reduce( (acc, cur, idx, arr )=> {
let
sum = acc.rating + cur.rating,
no = idx +1;
if (no === arr.length) { sum = sum / no };
return { 'name': cur.name, 'rating': sum }
});
console.log ('max =', Max_JSO)
console.log ('min =', Min_JSO)
max = { page: 1, totalPages: 2, data:
[ { title: 'Developer 1', rating: 4.7 }
, { title: 'Developer 2', rating: 7.8 }
]
}
min = { page: 1, totalPages: 2, data:
[ { title: 'Developer 1', rating: 4.7}
, { title: 'Developer 2', rating: 7.8}
]
}
I'm using this code right now, but I get a weird string as an output:
"max =", "{\"page\":1,\"totalPages\":5,\"data\":[{\"title\":\"Developer 1\",\"rating\":4.7},{\"title\":\"Developer 2\",\"rating\":7.8}]}"
"min =", "{\"page\":1,\"totalPages\":5,\"data\":[{\"title\":\"Developer 1\",\"rating\":4.7},{\"title\":\"Developer 2\",\"rating\":7.8}]}"
Is there any way to do this better?
Also, I need to not only read rating
from data
key, but also outside of it, as you can see on var myJSON
Like produce a resulting json
like this:
{
"Developer 1": 4.7,
"Developer 2": 7.8,
}
MIN being Developer 1
and MAX Developer 2