Greg Gum
Greg Gum

Reputation: 37895

Typescript Filter Array By Another Array

I need to filter one array of objects, by another array of objects. How do I do that with Typescript?

The below TS works except for the last line.

Goal: To get all vendors who service countyId = 1.

A Vendor can service more than one county.

There are three vendors, #1 in one county, #2 in two counties.

var all_vendors = [{ id: 1, name: 'A' }, { id: 2, name : 'B'}, { id: 3, name : 'c'}];
console.log('all vendors');
console.log(all_vendors);
var all_vendor_counties = [{ id: 1, vendorId: 1, countyId: 1 }, { id: 2, vendorId: 2, countyId: 1 }, { id: 3, vendorId: 2, countyId: 2 },];
console.log('All Vendor Counties')
console.log(all_vendor_counties);
var filtered_vendor_counties = all_vendor_counties.filter(a => a.countyId === 1);//return two vendor_counties.
console.log('Filtered Vendor Counties')
console.log(filtered_vendor_counties); 
//??? var allVendorsInCounty1 = all_vendors.filter( a=> //a is in filtered_vendor_counties)

Upvotes: 0

Views: 2007

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

First iterate over all_vendor_counties to create a Set containing all vendorIds you want to filter by, then filter the all_vendors array by whether the vendor's id is included in that Set:

var all_vendors = [{ id: 1, name: 'A' }, { id: 2, name : 'B'}, { id: 3, name : 'c'}];
var all_vendor_counties = [{ id: 1, vendorId: 1, countyId: 1 }, { id: 2, vendorId: 2, countyId: 1 }, { id: 3, vendorId: 2, countyId: 2 },];

const vendorIds = new Set(all_vendor_counties
  .filter(({ countyId }) => countyId === 1)
  .map(({ vendorId }) => vendorId)
);
const vendorsInCountyIds = all_vendors.filter(({ id }) => vendorIds.has(id));

console.log(vendorsInCountyIds);

(could also use an array and use .includes instead of the Set's .has, but .includes has higher computational complexity)

Upvotes: 1

Related Questions