I am working on an application that involves gathering input from users for ten questions using select drop down boxes. The values range from 1 to 5 for each question. Upon clicking the submit button, I collect all the input values and store them in an object which is then sent via a $.post request route. On the server side, I process the data by comparing it with an array of 'friends' scores and calculating the differences. My challenge lies in determining how to identify and return multiple 'friends' who have the same lowest score difference.
frontside.js
$('#submit').on('click', function(){
var newProfile = {
name: $('#name').val().trim(),
photo: $('#link').val().trim(),
scores: []
};
for(var x = 0; x < questions.length; x++){
var num = parseInt($('select[name = "q' + (x+1) + '"]').val());
newProfile.scores.push(num);
}
alert("Adding profile");
var currentURL = window.location.origin;
$.post(currentURL + "/api/friends", newProfile).done(function(data){
console.log('data', data);
});
server.js
var friends = require('./../data/friends.js');
app.post('/api/friends', function(req, res){
console.log('hi')
var person = req.body;
var diff = [];
var low = 0;
var match = [];
for(var x = 0; x < friends.candidates.length; x++){
for(var i = 0; i < friends.candidates[x].scores.length; i++){
var result = person.scores[i] - friends.candidates[x].scores[i];
if(result < 0){
var positive = result * (-1);
diff.push(positive);
}
else
diff.push(result);
}
//adding up the differences from each score
var added = diff.reduce(function(a, b){
return a + b;
}, 0);
//This is where I need to figure out how to store multiple lowest numbers of same value.
if(x === 0){
low = added;
match.push(friends.candidates[x]);
}
else if(low > added){
low = added;
match[0] = friends.candidates[x];
}
finalNum.push(added);
diff = [];
}
friends.candidates.push(person);
res.send(match);
});
friends.js
exports.candidates = [
{
scores:[5,1,4,4,5,1,2,5,4,1]
},
{
scores:[4,2,5,1,3,2,2,1,3,2]
},
{
scores:[5,2,2,2,4,1,3,2,5,5]
},
{
scores:[3,3,4,2,2,1,3,2,2,3]
},
{
scores:[4,3,4,1,5,2,5,3,1,4]
},
{
scores:[4,4,2,3,2,2,3,2,4,5]
},
{
scores:[2,3,3,3,3,3,3,3,3,3]
},
{
scores:[5,2,1,1,5,2,1,1,4,4]
}];