JavaScript Array.filter

The filter function in JavaScript will take an array, run a predicate against it, and return a new array containing the items that pass. It does not generally affect the original array.

class Car {
    constructor(year, make, model) {
        this.year = year;
        this.make = make;
        this.model = model;

// Normal use: filter the items

const cars = [
    new Car(1999, "Ford", "Bronco"),
    new Car(2020, "Chevy", "Blazer"),
    new Car(2015, "Toyota", "Prius"),
    new Car(2000, "Dodge", "Dakota"),
    new Car(2012, "Ford", "Mustang")

const newerCars = cars.filter(c => c.year > 2010);
console.log("Newer cars:")

The function accepts a second argument representing the position inside the array, in case you care about the index - useful for seeing if something is the first or last object, or for retrieving every Nth item

It also accepts a third argument of the array itself, which can get kind of funky, so personally I avoid that one.

View code on GitHub


Popular posts from this blog

DotNet CLI

Switch Expressions