Jayson H Jayson H - 1 year ago 126
Javascript Question

Using lodash to return an array of unique values while removing non unique

I'm trying to return the survey the visitor hasn't voted on, by survey_id. Using the example arrays below, I would expect survey_id: 4 to be returned.

What would be the best way to accomplish this?

Here are my example arrays:

// 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

Answer Source

You could use a combination of _.filter and _.find to apply a filter function to your survey collection, which filters out surveys when matching survey_id is found in votes collection. See this sample getUnansweredSurveys function:

function getUnansweredSurveys(surveys, votes) { 
  return _.filter(surveys, function(survey) { 
    return !_.find(votes, {survey_id: survey.survey_id})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download