Using .filter

Saturday, July 18, 2020

Having recently made a .map guide, it makes sense to make one for .filter as well.

What is .filter?

.filter is an array method that receives an condition to compare all the items in an array. If the condition passes, it will return that item to an array.

The old way

Let's say we want to return all the values that are higher than 4. How would we do that without using .filter? To give an idea, I made up an example that does this.

const arr = [1, 2, 4, 8, 16, 32];
const arrayToFill = [];
 
arr.forEach((num) => (num > 4 ? arrayToFill.push(num) : undefined));

Or even more verbose would be:

const arr = [1, 2, 4, 8, 16, 32];
const arrayToFill = [];
 
for (let index = 0; index < arr.length; index++) {
  const element = arr[index];
 
  if (element > 4) {
    arrayToFill.push(element);
  }
}

Using .filter

Let's look at the example below.

const arr = [1, 2, 4, 8, 16, 32];
const arrayToFill = arr.filter((num) => num > 4);

Does it look weird to you? All I told the code to check for is if the current number is higher than 4. That's because all .filter cares for if the condition on the current number is true. True means it gets passed to the array, false means discard.

Other usecases

You could also use .filter to filter through an array of objects.

() => {
  const arr = [
    { name: "Mo", age: 26 },
    { name: "Ann", age: 29 },
    { name: "John", age: 42 },
    { name: "Sarah", age: 22 },
  ];
  const olderThanTwentySix = arr.filter((person) => person.age > 26);
 
  return (
    <ul>
      {olderThanTwentySix.map((person) => (
        <li>{person.name}</li>
      ))}
    </ul>
  );
};