.filter() Method

First I want to shoutout @stolinski and @wesbos and their @syntaxfm podcast. It's a fantastic listen for anyone working in the web development/JavaScript/Node/React realm. I put it on when I'm riding the bus to work to get my mind thinking in code, and so when I get to the office and fire up my computer, my brain's already warmed up.

One of my favorite episodes is titled "20 JavaScript Array and Object Methods to make you a better developer." I've had it on the board to tackle each of these array methods in a blog post (though I may group some that are simple and similar). So with that being said, here we go!

The first array method I'm going to tackle is the .filter() method. Wes refers to this as a "poor man's search," and I think that's a super succinct way to think of it. .filter() is a method that takes a callback, which is some kind of condition, that is run against each item in the referenced array. The method produces a new array populated with items from the original array that meet the passed condition.

Examples:

Example 1:

const fruits = ["strawberry", "grape", "blueberry", "orange", "banana", "blackberry"];
const berries = fruits.filter(fruit => fruit.includes("berry"));
console.log(berries);
// expected output: Array ["strawberry", "blueberry", "blackberry"]

Example 2:

const people = [
  {
    name: "Joey",
    age: 30,
  },
  {
    name: "Odessa",
    age: 45,
  },
  {
    name: "Jordan",
    age: 25,
  },
];

const oldPeople = people.filter(person => person.age >= 28);
console.log(oldPeople);
// expected output: Array [Object { name: "Joey", age: 30 }, Object { name: "Odessa", age: 45 }]

From MDN: "The .filter() method creates a new array with all elements that pass the test implemented by the provided function."

See more examples and further documentation here.