Last active
January 10, 2020 13:36
-
-
Save frivolta/57e1d68df99cd5e8021cf6e8b174ad46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define a book type | |
type Book = { | |
title: string; | |
genre: string; | |
publicationYear: number; | |
}; | |
// Define a list of types | |
const listOfBooks: Book[] = [ | |
{ | |
title: | |
'Dragon Of The Titans', | |
genre: | |
'fantasy', | |
publicationYear: 1992, | |
}, | |
{ | |
title: | |
'Queen Of Spring', | |
genre: | |
'drama', | |
publicationYear: 2005, | |
}, | |
{ | |
title: | |
'Wolves Of The King', | |
genre: | |
'fantasy', | |
publicationYear: 1988, | |
}, | |
]; | |
// Use a common function to retrieve books | |
const filterArrayByValue = ( | |
items: Book[], | |
propertyName: string, | |
valueToFilter: string | |
): Book[] => { | |
return items.filter( | |
item => | |
item[ | |
propertyName | |
] === | |
valueToFilter | |
); | |
}; | |
// Call the function | |
// The result is an array with two books: "Dragon Of The Titans" and "Wolves Of The King" | |
console.log( | |
filterArrayByValue( | |
listOfBooks, | |
'genre', | |
'fantasy' | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment