Cover Image for Underscore.js _.filter Function
107 views

Underscore.js _.filter Function

The _.filter function in Underscore.js is used to create a new array containing elements from the original array that satisfy a given condition. It iterates over each element of the array and applies a predicate function to determine if the element should be included in the filtered result. Here’s an example of how to use _.filter:

JavaScript
var _ = require('underscore');

var numbers = [1, 2, 3, 4, 5];

var evenNumbers = _.filter(numbers, function(num) {
  return num % 2 === 0;
});

console.log(evenNumbers); // [2, 4]

In this example, we have an array numbers containing integers. We use _.filter to create a new array evenNumbers that contains only the even numbers from the original array.

The _.filter function takes two arguments: the array to be filtered and the predicate function. The predicate function is invoked with each element of the array, and it should return a boolean value indicating whether the element should be included in the filtered result (true) or not (false).

In the example, the predicate function checks if each number is divisible by 2 (num % 2 === 0). If it is, the function returns true, and the number is included in the evenNumbers array.

Note that Underscore.js can be used both in Node.js and in the browser. Make sure to include the Underscore.js library in your project before using its functions, and adjust the require statement accordingly if you’re using it in a Node.js environment.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS