Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter an array of objects by property JavaScript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading