Home > Blockchain >  Filter an array of objects by union types TypeScript
Filter an array of objects by union types TypeScript

Time:01-06

I have an array of objects like:

array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}]

I have defined union type

type NamesType = 'something' | 'bob'

Is it possible to filter the array by the types? So the final result would be

array = [{name: 'something'}, {name: 'bob'}]

CodePudding user response:

You can do this:

array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}];
namesType = ['something','bob'];
filteredArray = array.filter(item => namesType.includes(item.name));

CodePudding user response:

One example could be using Set like this:

const array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}]
const namesType = new Set(['something','bob']);
const filteredArray = array.filter(item => namesType.has(item.name));
console.log(filteredArray)

  • Related