I have an array of objects.
vehicles = [
{ "name": "Ford", "type": "SUV", "brand": "Explorer" },
{ "name": "Ford", "type": "SUV", "brand": "Explorer" },
{ "name": "Ford", "type": "truck", "brand": "F-150" },
{ "name": "Chrysler", "type": "car", "brand": "Sierra" },
{ "name": "GM", "type": "truck", "brand": "Sierra" },
{ "name": "GM", "type": "truck", "brand": "Sierra" },
]
How do I filter this by two properties of the objects so there is only one of each? Say name and brand have to be the same?
vehicles = [
{ "name": "Ford", "type": "SUV", "brand": "Explorer" },
{ "name": "Ford", "type": "truck", "brand": "F-150" },
{ "name": "Chrysler", "type": "car", "brand": "Sierra" },
{ "name": "GM", "type": "truck", "brand": "Sierra" },
]
This isn’t working:
const filteredVehicles = vehicles.filter((item) => item.name === name & item.brand === brand );
3
Answers
There are libraries that could help with this, but to do it with vanilla JavaScript, filter should be fine. In the example below filter is used to return elements where there are no elements later in the array that don’t match.
Feel free to change the expression inside of some to match by just the brand.
Here’s a generic function that you can supply an array of
props
to. It keeps track of the same props by using aSet
corresponding to each property, meaning it runs inO(nm)
time, wheren
is the length of the array andm
is the number of properties checked.Using reduce and Object.values to generate a unique key can filter on all the properties.
If you only want to filter on specific ones
If you want to be dynamic with the properties