Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example:

The array containing objects:

const persons = [
  {
    personId: 1,
    name: 'Patrick',
    lastName: 'Smith',
    age: 27,
    allergy: [
    {
      idAllergy: 1,
      name: 'Fish'
    },{
      idAllergy: 2,
      name: 'Nuts'
    }
    ]
  },
  {
    personId: 2,
    name: 'Lara',
    lastName: 'Blake',
    age: 21,
    allergy: [
    {
      idAllergy: 2,
      name: 'Nuts'
    }
    ]
  },
  {
    personId: 3,
    name: 'Erick',
    lastName: 'Robinson',
    age: 30,
    allergy: [
    {
      idAllergy: 3,
      name: 'Flowers'
    }
    ]
  },
  {
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [
    {
      idAllergy: 4,
      name: 'Chocolat'
    }
    ]
  }

]

The array with values for filtering:

// These are idAllergy let allergy = [2,3]

The goal is to use the values in the "allergy" array to search within the "persons" array and exclude individuals allergic to nuts and flowers. The expected result would be:

 [{
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [
    {
      idAllergy: 4,
      name: 'Chocolat'
    }
    ]
  }]

Appreciate any help provided.

Answer №1

const filtered = persons.filter(p => !p.allergy.some(a => allergy.includes(a.idAllergy)));

const individuals = [
    {
        personId: 1,
        name: 'Patrick',
        lastName: 'Smith',
        age: 27,
        allergy: [
            {
                idAllergy: 1,
                name: 'Fish'
            },{
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 2,
        name: 'Lara',
        lastName: 'Blake',
        age: 21,
        allergy: [
            {
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 3,
        name: 'Erick',
        lastName: 'Robinson',
        age: 30,
        allergy: [
            {
                idAllergy: 3,
                name: 'Flowers'
            }
        ]
    },
    {
        personId: 4,
        name: 'Hilda',
        lastName: 'Vianne',
        age: 35,
        allergy: [
            {
                idAllergy: 4,
                name: 'Chocolat'
            }
        ]
    }

]


let allergy = [2,3]

const filtered = individuals.filter(p => !p.allergy.some(a => allergy.includes(a.idAllergy)));

console.log(filtered);

Answer №2

Utilizing the filter function along with some can solve the problem at hand!

const people = [{
    personId: 1,
    name: 'Patrick',
    lastName: 'Smith',
    age: 27,
    allergy: [{
      idAllergy: 1,
      name: 'Fish'
    }, {
      idAllergy: 2,
      name: 'Nuts'
    }]
  },
  {
    personId: 2,
    name: 'Lara',
    lastName: 'Blake',
    age: 21,
    allergy: [{
      idAllergy: 2,
      name: 'Nuts'
    }]
  },
  {
    personId: 3,
    name: 'Erick',
    lastName: 'Robinson',
    age: 30,
    allergy: [{
      idAllergy: 3,
      name: 'Flowers'
    }]
  },
  {
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [{
      idAllergy: 4,
      name: 'Chocolat'
    }]
  }

]

const allergies = [2, 3]

const resultWithAllergies = people.filter(person => {
  const {
    allergy
  } = person;

  const hasAllergy = allergy.some(({
    idAllergy
  }) => allergies.includes(idAllergy))

  return hasAllergy;
})


console.log(resultWithAllergies)

const persons = [{
    personId: 1,
    name: 'Patrick',
    lastName: 'Smith',
    age: 27,
    allergy: [{
      idAllergy: 1,
      name: 'Fish'
    }, {
      idAllergy: 2,
      name: 'Nuts'
    }]
  },
  {
    personId: 2,
    name: 'Lara',
    lastName: 'Blake',
    age: 21,
    allergy: [{
      idAllergy: 2,
      name: 'Nuts'
    }]
  },
  {
    personId: 3,
    name: 'Erick',
    lastName: 'Robinson',
    age: 30,
    allergy: [{
      idAllergy: 3,
      name: 'Flowers'
    }]
  },
  {
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [{
      idAllergy: 4,
      name: 'Chocolat'
    }]
  }

]

const allergies = [2, 3];

const resultWithoutAllergies = persons.filter(person => {
  const {
    allergy
  } = person;

  const hasAllergy = allergy.some(({
    idAllergy
  }) => !allergies.includes(idAllergy))

  return hasAllergy;
})
console.log(resultWithoutAllergies)

Answer №3

To find individuals with allergies 2 and 3, follow these steps:

let selectedAllergies = [2,3];
const peopleWithAllergies = allPeople.filter(
   person => person.allergy.some(a => selectedAllergies.includes(a.idAllergy)));

const allPeople = [
    {
        personId: 1,
        name: 'Patrick',
        lastName: 'Smith',
        age: 27,
        allergy: [
            {
                idAllergy: 1,
                name: 'Fish'
            },{
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 2,
        name: 'Lara',
        lastName: 'Blake',
        age: 21,
        allergy: [
            {
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 3,
        name: 'Erick',
        lastName: 'Robinson',
        age: 30,
        allergy: [
            {
                idAllergy: 3,
                name: 'Flowers'
            }
        ]
    },
    {
        personId: 4,
        name: 'Hilda',
        lastName: 'Vianne',
        age: 35,
        allergy: [
            {
                idAllergy: 4,
                name: 'Chocolat'
            }
        ]
    }

]


const selectedAllergies = [2,3];
const peopleWithAllergies = allPeople.filter(person => person.allergy.some(a => selectedAllergies.includes(a.idAllergy)));

console.log(peopleWithAllergies);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...

Saving Json data to a variable

I am looking to store a JSON Object in a variable and format it with values like (JAN_2018, FEB_2018, etc.) and another set of values like (1081136328, 1069248328, etc.) Here's the code I have so far: var json = $.parseJSON(data); $(json ...

How to handle a property that is not found in a combined type in TypeScript?

In this scenario using TypeScript: interface EmotionsOkay { emotion: string; okay: "yap"; } interface EmotionsNotOkay { emotion: string; } type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay; const areYouOkay = (test: UndetereminedEmotion) =& ...

In Typescript, it is possible to provide values other than undefined for a parameter that is

I experimented with the code below in TypeScript Playground with all settings enabled. My expectation was that the TS compiler would only allow the first call() to be valid. However, to my surprise, all four calls were accepted. Upon inspecting the calls, ...

Exploring the process of obtaining a collection of JSON sub-items and using Angular's method for finding a match within an array

Question 1 In my program, I am receiving a JSON object called scope.tagSet, which has the structure shown below. { Tags : [ {"TagID" : "ID1" , "TagName" : "Name1"}, {"TagID" : "ID2" , "TagName" : "Name2"}, {"TagID" : "ID3 ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

Troubleshooting the Thumbs-Up and Thumbs-Down Voting System

My objective is to display multiple images on a single webpage and allow the general public to vote on them. I have implemented an AJAX command to hide the voting buttons and show a "thank you for your vote" message. This functionality works perfectly when ...

Post request in limbo

Looking for a way to delay post requests in Angular before they are sent? I've tried using pipe(delay(xxx)) and setTimeout, but haven't had any luck. Any suggestions on how to solve this issue? ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

Searching MySQL data with ng-repeat filter

I am facing a challenge in populating a div tag with ng-repeat and data from a MySQL database. My intention is to utilize ng-repeat for its filtering capabilities in the future. The dilemma lies in the integration of Angular and SQL. My desired HTML struc ...

What is the purpose of creating a new HTTP instance for Socket.io when we already have an existing Express server in place?

As I delve into SocketIO, I've combed through various blogs and documentation on sockets. It seems that in most cases, the standard approach involves creating an HTTP server first and then attaching the socket to it as shown below: var app = express() ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

The console is being flooded with API logging messages multiple times

My goal is to develop a search page for Pathfinder. I have crafted the following code in an attempt to retrieve data from the API. During the process of testing the fetch requests, I have noticed that when I console.log the fetched data, it appears multipl ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Angular backslash is encoded

Experiencing the same issue as this individual: angularjs-slash-after-hashbang-gets-encoded The URL is getting encoded and not routing correctly, causing it to fall to the otherwise in my route config. I have not been able to identify the root cause yet, ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

Using TypeScript to execute a function that generates middleware for an Express application

I've developed a middleware for validating incoming data, but I encountered an issue where a function that takes a Joi object as a parameter and returns the middleware is causing errors during build. Interestingly, everything works perfectly fine duri ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...