Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I am trying to filter null (undefined) element from an array by using Array.prototype.filter but TypeScript compiler does not seem to recognize the derived array of the "filter" function and failed to pass type check. , Use User-Defined Type Guards feature of TypeScript: const arry = [1, 2, 3, 4, "5", 6];
const numArry: number[] = arry
.filter((i): i is number => {
return typeof i === "number";
});
// numArry = [1, 2, 3, 4, 6]
|
Typescript Filter Array of Objects with an Array of Strings by Multiple Keywords
Date : March 29 2020, 07:55 AM
will be helpful for those in need I understand how to filter a single attribute in an array of an objects with just one keyword. I currently have a filter service that filters out an array of objects by a single attribute using a single keyword, but I cannot figure out how to do it with multiple keywords on an array of objects. This is what I have so far: , You can do it like this @Injectable()
export class PreferencesFilterService {
var preferencesList: string[] = ['Mexico', 'Brazil'];
getFilteredRestaurants(list: Restaurant[]): Restaurant[] {
return list.filter(function(restaurant) {
for (let tag in restaurant){
if (preferencesList.indexOf(restaurant[tag])!=-1){
return true;
}
}
return false;
});
}
}
|
TypeScript How to filter filter array of objects to single new object
Date : March 29 2020, 07:55 AM
I wish this help you const PickDetail = StopDetails.filter(detail => detail.TentativeNextPickFlag)[0]; This the easiest way to filter the array to only show the desired items.
|
How to use array filter based on index without using element callback in typescript
Date : March 29 2020, 07:55 AM
I hope this helps . I got the below error in tslint. , Use _ instead of x. _ means you don't need / care about this value.
|
Filter array in Typescript using functional programing [filter, map, some, reduce etc]
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I'm trying to work with functional programming , You should use filter method in combination with includes and map. let arr1=[{prodId:2},{prodId:4}], arr2=[{id:1, name:"Test1"}, {id:2, name:"Test2"}, {id:3, name:"Test3"}, {id:4, name:"Test4"}, {id:5, name:"Test5"}];
let ids = arr1.map(({prodId}) => prodId);
let result = arr2.filter(({id}) => ids.includes(id));
console.log(result);
let arr1=[{prodId:2},{prodId:4}], arr2=[{id:1, name:"Test1"}, {id:2, name:"Test2"}, {id:3, name:"Test3"}, {id:4, name:"Test4"}, {id:5, name:"Test5"}];
let result = arr2.filter(({id}) => arr1.some(({prodId}) => prodId == id));
console.log(result);
|