Filtering
This brings me to another insight: I need to use objects as array members when these objects have enough distinct data points to merit the use of an object. Otherwise, as with the example of a six-pack of beers, there's not really much distinction between any two items in that six-pack. Put differently, the reason to filter an array of objects in the first place, is essentially to find a sub-group of objects that share a specific property, which makes them different enough from all the other objects in this collection (array) of objects, to merit a use of a filter.
Now you should understand, at a conceptual level, why you might want to filter objects in an array, which brings me to explaining how you would go about doing it.
There are several built-in array methods that allow you to filter an array of items.
Using the array of users
, here's how I might filter them by country:
xxxxxxxxxx
const users = [
{ name: "Anna", email: "ana@ana.com", country: "United States" },
{ name: "Suzan", email: "suzan@suzan.com", country: "United Kingdom" },
{ name: "Barbara", email: "barb@barbara.com", country: "United States" },
];
const americans = users.filter((person) => person.country == "United States");
const brits = users.filter((person) => person.country == "United Kingdom");
console.log(
"In our list of users, the following come from the USA:",
americans
);
console.log(
"In our list of users, here are those that come from the UK:",
brits
);