Menu

Filter an array!

One of the most common actions is filtering an array to get some of the values of the array. Luckily javascript has a nice method for this. The filter() method.

With the following array of car brands we want to filter out the German brand.

const carBrands = [
  {
    brand: 'BMW',
    origin: 'Germany'
  },
  {
    brand: 'Fiat',
    origin: 'Italy'
  },
  {
    brand: 'Mercedes Benz',
    origin: 'Germany'
  },
  {
    brand: 'Ford',
    origin: 'USA'
  }
]
A snippet from a post template

To filter out only the German brand we can do this in the following way. The filter method takes each array item as a new variable called brand. Then we check if the brand origin is equal to 'Germany'. If that returns true the brand variable will be returned as an array item for the new germanBrands constant.

const germanBrands = carBrands.filter((brand) => brand.origin === 'Germany');
A snippet from a post template

The result of the new germanBrands constant is.

const carBrands = [
  {
    brand: 'BMW',
    origin: 'Germany'
  },
  {
    brand: 'Mercedes Benz',
    origin: 'Germany'
  }
]
A snippet from a post template

As you can see this makes filtering an array really easy.

Hello! šŸ‘‹