Usr
Usr

Reputation: 2848

Typescript filter array based on value from another array

This question has been asked many times, but I can't get it working.
I have two arrays, the first one is:

 first= [
      {
        id:1, descrizione: "Oggetto 1", 
        codiceAzienda: "Codice 1",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:2, descrizione: "Oggetto 2", 
        codiceAzienda: "Codice 2",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:3, descrizione: "Oggetto 3", 
        codiceAzienda: "Codice 3",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:4, descrizione: "Oggetto 4", 
        codiceAzienda: "Codice 4",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:5, descrizione: "Oggetto 5", 
        codiceAzienda: "Codice 5",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      }
    ]

and the second one is this:

second = [
          {
            id:1, descrizione: "Oggetto 1"
          },
          {
            id:3, descrizione: "Oggetto 3"
          }
        ]

What I want to achieve is to have an array with only the objects of the first that have the id equal to one of the object of the second. So the result would be:

final= [
          {
            id:1, descrizione: "Oggetto 1", 
            codiceAzienda: "Codice 1",
            dataInserimento:"01-01-2019",
            dataAggiornamento: "01-01-2019"
          },
          {
            id:3, descrizione: "Oggetto 3", 
            codiceAzienda: "Codice 3",
            dataInserimento:"01-01-2019",
            dataAggiornamento: "01-01-2019"
          }
        ]

I've tried doing this:

final= first.filter(ogg => second.map(y => y.id).includes(ogg.id));

but as a result I have all the objects of the first array. I've also tried with array.some():

final= first.filter(ogg => second.some(id => ogg.id == id));

In this case, the final array is empty.
Example of the second case

Upvotes: 2

Views: 146

Answers (1)

Ben Smith
Ben Smith

Reputation: 20240

This will work:

const final = first.filter(x => second.find(y => y.id === x.id))

You can see this working here.

Upvotes: 1

Related Questions