I have a mongoose schema which looks like this:
const ratesSchema = new Schema({
voter: {
type: Schema.Types.ObjectId, ref: 'User'
},
project: {
type: Schema.Types.ObjectId, ref: 'Project'
},
votes:{
participant:{
type: Schema.Types.ObjectId, ref: 'User'
},
criteria1: Number,
criteria2: Number,
criteria3: Number,
criteria4: Number,
criteria5: Number,
criteria6: Number,
criteria7: Number,
criteria8: Number,
criteria9: Number,
criteria10: Number,
criteria11: Number,
criteria12:String,
average: Number
}
})
and in express i'm trying to calculate an average for each participant based on their avg rates for first 10 Criteria and 11th :
const avg = (args) => args.reduce((a, b) => a b) / args.length;
router.post('/:id/rate', isLogedIn, catchAsync(async(req, res, next) => {
const{project, voter, participants, criteria1, criteria2, criteria3, criteria4, criteria5, criteria6, criteria7, criteria8,criteria9, criteria10, criteria11, criteria12} = req.body
for(let i= 0; i < participants.length; i ){
const rate = new Rates({
project,
voter,
votes:{
participant: participants[i],
criteria1: criteria1[i],
criteria2: criteria2[i],
criteria3: criteria3[i],
criteria4: criteria4[i],
criteria5: criteria5[i],
criteria6: criteria6[i],
criteria7: criteria7[i],
criteria8: criteria8[i],
criteria9: criteria9[i],
criteria10: criteria10[i],
criteria11: criteria11[i],
criteria12: criteria12[i],
average: avg([avg([criteria1[i], criteria2[i], criteria3[i], criteria4[i], criteria5[i], criteria6[i], criteria7[i], criteria8[i], criteria9[i], criteria10[i]]), criteria11[i]])
}
})
console.log(rate.votes.average)
}
res.send('hi')
}));
The problem is that it doesn't count averag right for example if all criterias are rated with 8 it will calculate average as: 4444444
Can someone help me solve the problem (i'm new to programming)
CodePudding user response:
you should convert your data to int
you are adding criteria1[i] as string not int
you should convert it to int by parseInt()
there is two way
1 :
const avg = (args) => args.reduce((a, b) => parseInt(a) parseInt(b)) / args.length;
2 :
avg([avg([parseInt(criteria1[i])...), parseInt(criteria11[i]])) // do it for all criteria