我有一个应用程序,通过选择下拉框接收十个问题的值。每个下拉菜单的值为1 - 5。当用户单击提交按钮时,我将输入框中的所有值存储在对象中,然后将它们发送到$ .post请求路由。在服务器端的这个发布请求路由中,我获得发送到服务器的发布数据,并循环通过“朋友”阵列,将每个得分数组减去用户选择的分数。我需要记录哪个朋友差异最小并将其发回去,但我无法弄清楚如何发回多个朋友'可能具有相同的最低编号。
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]
}];
答案 0 :(得分:0)
试试这个。
// holds the minimum difference
var minDiff = Number.MAX_SAFE_INTEGER;
// holds the list of friends with minimum difference
var minDiffFriends = [];
for(var x = 0; x < friends.candidates.length; x++){
// variable to hold sum of differences
var scoreSum = 0
for(var i = 0; i < friends.candidates[x].scores.length; i++){
var result = person.scores[i] - friends.candidates[x].scores[i];
if(result < 0){
result = result * (-1);
}
scoreSum += result;
}
if(scoreSum < minDiff) {
minDiff = scoreSum ;
//clear previous array
minDiffFriends.length = 0;
//add the current friend information
minDiffFriends.push(friends.candidates[x]);
}
else if(scoreSum ==minDiff) {
// store friend information
minDiffFriends.push(friends.candidates[x]);
}
}