How to Use the Array filter() Method in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to use the array filter() method in JavaScript.

The filter() method

The filter() is a method to narrow down the contents of an array by specific conditions.
It is used to judge each element under the condition specified by the callback function and extract only the element that meets the condition.

Sponsored links

filter() usage

When using filter, specify the filter method for the array.

array.filter(callback [,that]);

For "array", specify the array object created in advance.
In callback, you can specify the value of the array element, the numerical index of the array element, and the array object that stores the array element.

For each array element, the element for which callbak returns true is generated as a new array.

The following are samples that get a specific condition from an array using the filter method.

Get only odd numbers from the array

var data = [1, 4, 5, 12, 19];
var result = data.filter(function(value) {
  return value % 2 === 1;
});
console.log(result);
//result
//[1, 5, 19]

Exclude numbers less than 6 from the array

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function isMinNum(value) {
  return (value >= 6);
}
var filterNum = numbers.filter(isMinNum);
console.log(filterNum);
//result
//[6, 7, 8, 9]

Get the character string that meets the condition from the array

var items = ["item1", "item2", "item3"];
var filterItems = items.filter(function(value) {
  return value === "item2";
});
console.log(filterItems);
//result
//["item2"]