Last active
June 4, 2020 14:53
-
-
Save vanaf1979/a889471c388089e64c502deeb7d19846 to your computer and use it in GitHub Desktop.
How to use Array.prototype.filter() to search for objects in an array/api response by object key/value.
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
// MDN Docs: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | |
const trekkies = [ | |
{ id: 0, name: "Piccard", planet: "Earth" }, | |
{ id: 1, name: "Spock", planet: "Vulcan" }, | |
{ id: 2, name: "Kirk", planet: "Earth" }, | |
{ id: 3, name: "Worf", planet: "Gault" } | |
]; | |
const findTrekkiesByPlanet = planet => { | |
return trekkies.filter(trekkie => trekkie.planet === planet); | |
}; | |
console.log(findTrekkiesByPlanet("Earth")); | |
// [0: Object {id: 0 name: "Piccard" planet: "Earth"} | |
// 1: Object {id: 2 name: "Kirk" planet: "Earth"}] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment