Skip to content

Instantly share code, notes, and snippets.

@vanaf1979
Last active June 4, 2020 14:53
Show Gist options
  • Save vanaf1979/a889471c388089e64c502deeb7d19846 to your computer and use it in GitHub Desktop.
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.
// 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