0
私はドロップダウンボックスを使って10個の質問の値を取るアプリケーションを持っています。各ドロップダウンメニューの値は1〜5です。ユーザーが送信ボタンをクリックすると、入力ボックスのすべての値がオブジェクトに格納され、$ .post要求ルートに送信されます。サーバー側のこのポストリクエストルート内で、私はサーバーに送信されたポストデータを取得し、ユーザーが選択したスコアに各スコア配列を引く 'friends'の配列をループします。どの友達が最も差が少ないかを記録して送り返す必要がありますが、同じ番号の同じ複数の「友人」を返信する方法はわかりません。配列内のすべての小数点を見つける
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]
}];
diffで並べ替えると、同じdiffを持つ最後からすべてを取ります。 – dandavis
diff配列は、ユーザスコア配列とfriends [x] .scores配列からの各減算された数の差を保持する一時配列です。これが完了した後にリセットする必要があります。それ以外の場合は、得点 – henhen