The filter() method for Array instances generates a shallow duplicate of a specified array segment. This duplicate contains only those elements from the original array that satisfy the conditions set by the provided function.

Syntax:

filter(callbackFn)
filter(callbackFn, thisArg)

callbackFn:

A callback function intended to be executed for each element within the array. It is expected to return a truthy value if the element is to be retained in the resulting array, and a falsy value otherwise. The function is invoked with the following arguments:
element:
The current element being processed in the array
index:
The index of the current element being processed in the array
array:
The array filter() was called upon

thisArg(Optional):

A value to use as this when executing callbackFn

Return value:

A shallow replica of the provided array, comprising only the elements that meet the specified condition. In case no elements satisfy the condition, an empty array is returned.

Description:

The filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value.
Array elements which do not pass the callbackFn test are not included in the new array. Read the iterative methods section for more information about how these methods work in general.

Basic Example:

const words = ["apple", "banana", "carrot", "dog", "elephant", "forest", "guitar", "helicopter"]
const result = words.filter((word) => word.length > 6);
console.log(result);

Expected output: [‘elephant’, ‘helicopter’]

Example to filter out big values:

function isBigEnough(value) {
  return value <= 12;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
console.log(filtered)

Expected output: [12, 5, 8]

AngularJS Example:

In AngularJS, the filter filter is commonly used to filter arrays based on certain criteria. Here’s an example of how you can use the filter filter in an AngularJS application:

Let’s say you have an array of objects representing a list of products, and you want to filter the products based on a user-entered search term.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>AngularJS Filter Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="myController">
  <h2>Product List</h2>

  <input type="text" ng-model="searchTerm" placeholder="Search">

  <ul>
    <li ng-repeat="product in products | filter:searchTerm">
      {{ product.name }} - {{ product.price | currency }}
    </li>
  </ul>

  <script>
    var app = angular.module('myApp', []);

    app.controller('myController', function($scope) {
      $scope.products = [
        { name: 'Laptop', price: 1200 },
        { name: 'Smartphone', price: 800 },
        { name: 'Tablet', price: 500 },
        { name: 'Headphones', price: 100 }
      ];
    });
  </script>

</body>
</html>

In this example:

  1. We have an AngularJS application defined with the module name ‘myApp’.
  2. The controller ‘myController’ is attached to the body element using ng-controller.
  3. We have an input field (ng-model=”searchTerm”) where the user can enter a search term.
  4. The ng-repeat directive is used to loop through the products array, and the filter filter is applied to filter the products based on the searchTerm.
  5. The filtered list of products is displayed in an unordered list (<ul>).
  6. As the user types in the search input, AngularJS will automatically filter the list of products based on the entered search term.

Angular 2+ Example:

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  private data = [
    {
      full_name: 'Jenny',
      phone_number: '8458 7098',
      gender: 'Female',
    },
    {
      full_name: 'Howard',
      phone_number: '8845 5888',
      gender: 'Male',
    },
  ];

  // variable to access from the template
  public maleCount = 0;

  ngOnInit(): void {
    // triggers the "getMaleCount" method only once.
    this.maleCount = this.getMaleCount(this.data);
  }

  getMaleCount(data): number {
    return data.filter((entry) => entry.gender === 'Male').length;
  }
}

app.component.html

Male Count: {{ maleCount }}

In this example:

  1. In this example we have data of different users.
  2. The ngOnInit method sets the maleCount property by calling the getMaleCount method with the data array.
  3. getMaleCount method takes an array of data as a parameter, filters the array to include only objects with a gender property set to ‘Male’, and then returns the count of objects.
  4. The result is assigned to the maleCount property.
  5. Finally on app.component.html we are printing the total count of maleCount.

Support On Demand!

                                         
Angular