Search code examples
javascriptlodash

lodash: array filter and exclude by object


I have an Array a of Questions:

[
  {id: 1,name: "Question 1"},
  {id: 2,name: "Question 2"},
  {id: 3,name: "Question 3"},
]

and an Array b of Answers, where the property question_id references the property id of Array a:

[
  {id: 1, question_id: 2,name: "My Answer to Question 2"}
]

With lodash, I want to filter Array a to exlude all the Answers that are referencing to it, expecting the output:

[
  {id: 1,name: "Question 1"},
  {id: 3,name: "Question 3"},
]

Solution

  • var questions = [
        {id: 1,name: "Question 1"},
        {id: 2,name: "Question 2"},
        {id: 3,name: "Question 3"},
    ];
    
    var answers = [
        {id: 1, question_id: 2,name: "My Answer to Question 2"}
    ];
    
    var filtered = _.filter(questions, isNotReferencedByAnyAnswer);
    
    function isNotReferencedByAnyAnswer(question) {
        return _.findIndex(answers, {'question_id': question.id}) === -1;
    }