我试图通过survey_id返回访问者尚未投票的调查。使用下面的示例数组,我希望返回survey_id:4。
实现这一目标的最佳方法是什么?
以下是我的示例数组:
// Survey Object
[{
survey_id: 1,
name: 'Survey 1",
question: "This is a survey question"
}, {
survey_id: 2,
name: 'Survey 2",
question: "This is a another survey question"
}, {
survey_id: 3,
name: 'Survey 3",
question: "This is a another 3 survey question"
}, {
survey_id: 4,
name: 'Survey 4",
question: "This is a another 4 survey question"
}]
// Votes
[{
vote_id: 11,
visitor_token: "aDe4GggAe3",
survey_id: 1
}, {
vote_id: 12,
visitor_token: "aDe4GggAe3",
survey_id: 2
}, {
vote_id: 13,
visitor_token: "aDe4GggAe3",
survey_id: 3
}]

答案 0 :(得分:2)
接受的答案有O(n ^ 2)时间复杂度。如果性能很重要,应该避免相互嵌套的线性操作 - 如果有利于代码的简洁性,@ SD'答案更清晰。这是一个带有vanilla JavaScript和线性时间O(n)复杂度的版本。
function surveysWithNoVotes(surveyList, voteList) {
var surveyIds = surveyList.map(function(survey) {
return survey.survey_id
})
var votedForIdsMap = voteList.reduce(function(memo, vote) {
memo[vote.survey_id] = vote.survey_id
}, {})
return surveyIds.filter(function(id) {
return !votedForIdsMap[id]
})
}
答案 1 :(得分:0)
您可以使用_.filter
和_.find
的组合将过滤功能应用于您的调查集合,该调查集合会在投票收集中找到匹配survey_id
时筛选出调查。请参阅此示例getUnansweredSurveys
函数:
function getUnansweredSurveys(surveys, votes) {
return _.filter(surveys, function(survey) {
return !_.find(votes, {survey_id: survey.survey_id})
})
}