Anand
Anand

Reputation: 1671

How do I filter a typescript array with items in another array

I have 2 arrays:

 [
  {
    "id": 1,
    "name": "All",
  },
  {
    "id": 2,
    "name": "APR",
  },
 {
    "id": 3,
    "name": "TER",
  }]

The second array is ["APR", "TER"]

I want to filter the first array with the second that is the output should be

  [{
    "id": 2,
    "name": "APR",
  },{
    "id": 3,
    "name": "TER",
  }]

Trying this with filter function - is that possible?

Thanks Anand

Upvotes: 0

Views: 7212

Answers (2)

Atemu
Atemu

Reputation: 152

You can filter your array with the filter function:

const items =  [
  {
    "id": 1,
    "name": "All",
  },
  {
    "id": 2,
    "name": "APR",
  },
 {
    "id": 3,
    "name": "TER",
  }]

const filterValues = ["APR", "TER"]

const filtered = items.filter(item => filterValues.indexOf(item.name) > -1)

Upvotes: 2

CRice
CRice

Reputation: 32146

Pretty standard use of the filter method. Just give it the right condition to check, and you're good to go:

const myArray = [{
  "id": 1,
  "name": "All",
}, {
  "id": 2,
  "name": "APR",
}, {
  "id": 3,
  "name": "TER",
}];

const otherArray = [
  "APR",
  "TER",
];

const filtered = myArray.filter(x => otherArray.includes(x.name));

console.log(filtered)

Upvotes: 5

Related Questions