Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.