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 one of the properties of the objects so there is only one of each? Say by brand?
vehicles = [
{ "name": "Ford", "type": "SUV", "brand": "Explorer" },
{ "name": "Ford", "type": "truck", "brand": "F-150" },
{ "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(name = x.name & brand = x.brand );
>Solution :
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.
const 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" },
];
const reduced = vehicles.filter((el, i, ary) => !ary.slice(i + 1)
.some(x => x.name === el.name && x.brand === el.brand));
console.log(reduced);
Feel free to change the expression inside of some to match by just the brand.